当DataGridTextColumn值改变时,如何更改DataGridCheckBoxColumn值?

时间:2013-01-20 14:44:09

标签: wpf mvvm datagrid

我正在使用带有mvvm的wpf,我有一个包含4列的数据网格: ID,原创,翻译,IsTranslated 我希望当Translated列中的文本发生变化时,IsTranslated列的值会自动更改为已选中 这是我的datagrid xaml代码:

<DataGrid Grid.Row="3" AutoGenerateColumns="False" ItemsSource="{Binding AllXliffs}">
            <DataGrid.Columns>
                <DataGridTextColumn Header="ID" Binding="{Binding Path=Id}" />
                <DataGridTextColumn Header="Original" Binding="{Binding Path=Original}" />
                <DataGridTextColumn Header="Translated" Binding="{Binding Path=Translated}" />
                <DataGridCheckBoxColumn Header="IsTranslated"  Binding="{Binding Path=IsTranslated, Mode=TwoWay, Converter={StaticResource StringToBooleanConverter}, UpdateSourceTrigger=PropertyChanged}" ></DataGridCheckBoxColumn>
            </DataGrid.Columns>
</DataGrid> 

3 个答案:

答案 0 :(得分:1)

由于您正在使用MVVM,因此您可以在模型属性中添加小型业务逻辑:

像这样:

        private string _translation;
        private bool _isTranslated;

        public string Translation
        {
            get { return _translation; }
            set
            {
                _translation = value;
                IsTranslated = !String.IsNullOrEmpty(_translation);
            }
        }

        public bool IsTranslated
        {
            get { return _isTranslated; }
            set
            {
                _isTranslated = value;
                OnPropertyChanged("IsTranslated");
            }
        }

答案 1 :(得分:0)

您应该将IsTranslated列绑定到Translated绑定路径,而不是IsTranslated绑定路径。

答案 2 :(得分:0)

试试这个:

 <Window.Resources>
        <loca:StringToBooleanConverter x:Key="myCon" />
    </Window.Resources>
    <Grid>
        <DataGrid Grid.Row="3" AutoGenerateColumns="False" ItemsSource="{Binding}">
            <DataGrid.Columns>
                <DataGridTextColumn Header="ID" Binding="{Binding Path=Id}" />
                <DataGridTextColumn Header="Original" Binding="{Binding Path=Original}" />
                <DataGridTextColumn Header="Translated" Binding="{Binding Path=Translated}" />
                <DataGridCheckBoxColumn Header="IsTranslated"  Binding="{Binding Path=Translated, Converter={StaticResource myCon}, UpdateSourceTrigger=PropertyChanged}" />
            </DataGrid.Columns>
        </DataGrid>
    </Grid>

转换器应如下所示:

public class StringToBooleanConverter: IValueConverter
{
        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            string translated = (string)value;
            if (string.IsNullOrEmpty(translated))
                return false;
            else
                return true;
        }

        public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {            
            return Binding.DoNothing;
        }
}