【问题标题】:Use IValueConverter within WPF DataGrid depending on several values of the same row根据同一行的多个值在 WPF DataGrid 中使用 IValueConverter
【发布时间】:2013-10-08 15:42:24
【问题描述】:

我正在开发一个遵循 MVVM 模式的 WPF 项目。我确实有以下模型:

名称...¦.Value.¦.Unit.¦.Type.¦.Min.¦.Max.¦

电压…………3………………mV………………X……………………0……………………5…… .¦

电流¦.....1.....¦...mA..¦....Y....¦...2...¦....7... .¦

这是数据网格显示的内容:

名称...¦.Value.¦.Unit.¦

电压¦..3........¦.mV..¦

电流¦..1....¦.mA..¦

模板(XAML):

<DataTemplate x:Key="NumTemplate">
        <wpfToolkit:IntegerUpDown Value="{Binding Value, UpdateSourceTrigger=PropertyChanged, Converter={StaticResource StimVoltageConverter},ConverterParameter=XXX}" />
    </DataTemplate>

    <DataTemplate x:Key="ComboboxTemplate">
        <ComboBox ItemsSource="{Binding Path=XXX}" 
DisplayMemberPath="Name" 
SelectedValuePath="Value" 
SelectedValue="{Binding Value, UpdateSourceTrigger=PropertyChanged}" />
    </DataTemplate>

数据网格(XAML):

<DataGrid ItemsSource="{Binding FixParaCollectionView}"  AutoGenerateColumns="False">
    <DataGrid.Columns>
          <DataGridTextColumn IsReadOnly="True" Header="Name" Binding="{Binding Id}"/>
          <DataGridTemplateColumn Header="Value">
              <DataGridTemplateColumn.CellTemplateSelector>
                  <helper:TemplateSelector ComboboxTemplate="{StaticResource ComboboxTemplate}" NumTemplate="{StaticResource NumTemplate}"/>
              </DataGridTemplateColumn.CellTemplateSelector>
           </DataGridTemplateColumn>
           <DataGridTextColumn Header="Unit" Binding="{Binding Unit,NotifyOnTargetUpdated=True}">
           </DataGridTextColumn>
    </DataGrid.Columns>
</DataGrid>

StimVoltageConverter:IValueConverter:

public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        int val = (int)value;

        return (int)(val / 0.41);
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        int val = (int)value;
        return (int)(val * 0.41);
    }

我现在想做两件事:

  1. 根据同一行的另一个值(例如“名称”或“类型”)转换值(例如,如果 Type==X,则为 Value*0.41)

  2. 我想验证写入数据网格的值(由用户)(例如验证模型的最小/最大值)

我在“NumTemplate”模板中添加了一个转换器。

使用转换器/验证来做这件事是个好主意吗?我真的很想在转换器中实现它,因为它与所有其他逻辑很好地分开。

提前致谢。

【问题讨论】:

    标签: c# wpf mvvm datagrid ivalueconverter


    【解决方案1】:

    对于验证,您希望在属性绑定上使用验证功能。

    就计算值而言,如果我有计算值,我通常会避免使用依赖属性。通常更喜欢 INotifyPropertyChanged。 int Value { get { computation...; } set { reverse computation...; PropertyChanged("Value");}}

    您可以在依赖项的父值和 PropertyChanged(new PropertyChangedArgs("Value")); 上收到 propertychanged 通知

    事实上,我通常避免在视图模型上使用 DependencyProperties。

    【讨论】:

    • 如何在 ValueConverter 中获取同一行的其他值?
    猜你喜欢
    • 1970-01-01
    • 2014-08-25
    • 2013-09-05
    • 2013-11-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-23
    • 2020-05-21
    相关资源
    最近更新 更多