开发者

WPF CheckBox not getting checked at initiation (data binding)

I've just come across this problem with my CheckBox data binding. The scenario is:

When I initialize the user interface (start the application), the CheckBoxes are unchecked, although the property they are bound to is set to true. When I click the CheckBox, the property is set to false, but the CheckBox is still shown as unchecked. From now on, the data binding works as expected and the CheckBox is correctly synched with the binding property.

Here's my XAML code:

<ItemsControl ItemsSource="{Binding Path=DisplayTypes}">
    <ItemsControl.ItemsPanel>
        <ItemsPanelTemplate>
            <WrapPanel />
        </ItemsPanelTemplate>
    </ItemsControl.ItemsPanel>
    <ItemsControl.ItemTemplate>
        <DataTemplate DataType="{x:Type Presentation:TypeDisplayPair}">
            <CheckBox IsChecked="{Binding Display}" Margin="3">
                <TextBlock Text="{Binding Type}" Foreground="开发者_Python百科{Binding Color}" />
            </CheckBox>
        </DataTemplate>
    </ItemsControl.ItemTemplate>
</ItemsControl>

And my view model:

public class TypeDisplayPair : BaseViewModel
{
    private bool display;
    private readonly Brush color;

    public TypeDisplayPair(string type, bool display)
    {
        Display = display;
        Type = type;
        color = BrushGenerator.GetRandomSolidColorBrush();
    }

    public string Type { get; set; }

    public bool Display
    {
        get { return display; }
        set
        {
            display = value;
            this.FirePropertyChanged(x => x.Display);
        }
    }

    public Brush Color
    {
        get { return color; }
    }
}

Any suggestions are appreciated, as I've spent too much time debugging this and I've run out of ideas.


The code you provided is perfectly correct, you initialization problem probably comes from the way you assign the DataContext. I've tried the following:

    public Window1()
    {
        DataContext = this;
        DisplayTypes = new ObservableCollection<TypeDisplayPair>()
        {
            new TypeDisplayPair("Alpha", true),
            new TypeDisplayPair("Beta", false)
        };

        InitializeComponent();
    }

and it works as expected.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜