简体   繁体   中英

C# and WPF: Programmatic Control

I'm learning WPF, and seem to have found something a little odd, which I can't find the reason to anywhere I've searched.

I have a window with one checkbox on it called "chkTest". I have it set to be true by default.

The following code is what I don't understand. Basically I'm trying to set the "chkTest" control to a control I create on the fly. The message box displays the value I set in code, but the control on the window is still set to be true.

Can someone explain the process behind this?

public partial class Window1 : Window
{
    public Window1()
    {
        InitializeComponent();

        CheckBox chk = new CheckBox();
        chk.IsChecked = false;

        this.chkTest = chk;

        MessageBox.Show(chk.IsChecked.Value.ToString());
    }
}

Thanks

This is because you're fooling the DependencyProperty system by doing this - remember, getters/setters of DP properties work differently than regular properties. The UI has a trigger on the IsChecked property, but you replace the whole object. Since you didn't actually change IsChecked on the visible checkbox, the trigger doesn't fire and the UI isn't updated.

Here's one way to go about it. First, you give a name to your main Grid - say, LayoutRoot:

<Grid x:Name="LayoutRoot">
    <CheckBox x:Name="chkTest" IsChecked="True"></CheckBox>
</Grid>

Then, you say:

public partial class Window1 : Window
{
    public Window1()
    {
        InitializeComponent();

        CheckBox chk = new CheckBox();
        chk.IsChecked = false;

        LayoutRoot.Children.Remove(chkTest);
        LayoutRoot.Children.Add(chk);
    }
}

And you're done.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM