【问题标题】:WPF CheckBox not getting checked at initiation (data binding)WPF CheckBox 在启动时未得到检查(数据绑定)
【发布时间】:2009-11-26 08:56:20
【问题描述】:

我刚刚在CheckBox 数据绑定中遇到了这个问题。场景是:

当我初始化用户界面(启动应用程序)时,CheckBoxes 未选中,尽管它们绑定的属性设置为 true。当我单击CheckBox 时,该属性设置为false,但CheckBox 仍显示为未选中。从现在开始,数据绑定按预期工作,CheckBox 与绑定属性正确同步。

这是我的 XAML 代码:

<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="{Binding Color}" />
            </CheckBox>
        </DataTemplate>
    </ItemsControl.ItemTemplate>
</ItemsControl>

还有我的视图模型:

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; }
    }
}

感谢任何建议,因为我花了太多时间调试它,而且我已经没有想法了。

【问题讨论】:

    标签: c# wpf data-binding mvvm checkbox


    【解决方案1】:

    您提供的代码完全正确,您的初始化问题可能来自您分配DataContext 的方式。我尝试了以下方法:

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

    它按预期工作。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-09-22
      • 1970-01-01
      • 2020-08-14
      • 1970-01-01
      相关资源
      最近更新 更多