【问题标题】:DataGrid creating RadioButton columnDataGrid 创建 RadioButton 列
【发布时间】:2011-07-22 07:46:30
【问题描述】:

我将对象绑定到 DataGrid。我创建了一个绑定到对象的 Is Default 属性的单选按钮列。

当应用启动时,默认显示正确的项目,但是绑定永远不会更新。我希望用户选中一个单选框并将该对象变为默认值。

        <DataGrid CanUserAddRows="False" AutoGenerateColumns="False" Name="TEst" >
        <DataGrid.Columns >
            <DataGridTextColumn Header="Value" Binding="{Binding Path=Name, Mode=OneTime}"/>

            <DataGridTemplateColumn Header="Is Default">
                <DataGridTemplateColumn.CellTemplate>
                    <DataTemplate>
                        <RadioButton GroupName="Test" IsChecked="{Binding IsDefault}" />
                    </DataTemplate>
                </DataGridTemplateColumn.CellTemplate>
            </DataGridTemplateColumn>

        </DataGrid.Columns>
    </DataGrid>

 private class Test : INotifyPropertyChanged
    {
        public string Name
        {
            get;
            set;
        }
        bool isDefult;
        public bool IsDefault
        {
            get
            {
                return isDefult;
            }
            set
            {
                isDefult = value;
            }
        }

        public event PropertyChangedEventHandler PropertyChanged;
    }

    public MainWindow()
    {
        this.InitializeComponent();
        Test[] ya = new Test[] { new Test { Name = "1", IsDefault = false }, new Test { Name = "2", IsDefault = false }, new Test { Name = "3", IsDefault = true } };

        this.TEst.ItemsSource = ya;
    }

为此,我整个下午都在拉头发。任何帮助都会受到欢迎。

【问题讨论】:

    标签: .net wpf .net-4.0 binding wpfdatagrid


    【解决方案1】:

    这很奇怪,但你要做的就是改变 RadioButton 的绑定:

    <RadioButton GroupName="Test" IsChecked="{Binding IsDefault, UpdateSourceTrigger=PropertyChanged}" />
    

    据我所知,默认值是LostFocus,但是DataGrid里面的focus有一些问题。我不知道为什么会出现问题。

    还有一个问题:在IsDefault 属性的设置器中引发PropertyChanged 事件。现在一切正常,无需通知,但如果您添加更多 xaml 代码,将很难找出 UI 未更新的原因。

    【讨论】:

    • 感谢您让我免于将头撞在桌子上。
    【解决方案2】:

    在这里设置UpdateSourceTrigger=PropertyChanged 是不够的。你还需要Mode=TwoWay

    【讨论】:

      猜你喜欢
      • 2014-06-16
      • 2017-02-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-09-07
      • 2018-05-20
      • 2013-06-27
      相关资源
      最近更新 更多