开发者

DataGrid creating RadioButton column

开发者 https://www.devze.com 2023-02-20 02:43 出处:网络
I have objects bound to a DataGrid. I have created a radio button column bound to the Is Default property of the object.

I have objects bound to a DataGrid. I have created a radio button column bound to the Is Default property of the object.

When the app starts up the correct item is shown as default, however the binding is then never updated. The behaviour I would like is for the user to check a radio box and for that object to become the 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>
            开发者_JS百科        <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;
    }

I’ve been pulling my hair out all afternoon at this. Any help would be loved.


It's quite strange, but all that you have to do is to change the binding of the RadioButton:

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

As far as I know, the default value is LostFocus, but there are some problems with focus inside DataGrid. I don't know why the problem happens.

And another issue: raise the PropertyChanged event inside the setter of the IsDefault property. Now everything works fine without notifications, but if you add more xaml code it will be dificult to find out why the UI isn't updated.


Setting UpdateSourceTrigger=PropertyChanged is not enough here. You also need Mode=TwoWay

0

精彩评论

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

关注公众号