tags:

views:

748

answers:

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 widow 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

+3  A: 

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.

Paul Betts
A: 

Ok, that makes sense -- would you happen to have a good reference on how to do what I'm attempting properly?

I'm about a week and a half into the WPF world, so please bear with me :)

Thanks

Why are you trying to replace controls on your UI at runtime anyways?
Paul Betts
+2  A: 

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.

Boyan