3

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

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

Comments

3

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.