【问题标题】:How do you bind a viewmodel which implements IDataErrorInfo to a UserControl and propagate the validation errors?如何将实现 IDataErrorInfo 的视图模型绑定到 UserControl 并传播验证错误?
【发布时间】:2011-04-26 12:36:20
【问题描述】:

我编写了一个 UserControl,它公开了一些依赖属性来修改控件的布局(即,将其视为通用类型安全的编辑器控件 - 所以我的数据类型是日期(通过日期选择器编辑),枚举(通过组合框编辑)和数字(通过文本框编辑)。我还将 3 个编辑器控件的值公开为依赖属性,以便它可以进行数据绑定。

用户控件中的控件都绑定到公开的依赖属性以获取它们的值(必要时使用适当的转换器)。

该控件构成了绑定到视图模型的较大 UI 的一小部分 - 要编辑的值、自定义控件的数据类型标志和可能的有效值列表都绑定到视图模型中的对象。

我的问题是这样的:我在 viewmodel 上实现了 IDataErrorInfo 并将自定义用户控件中的控件绑定设置为具有 ValidatesOnDataErrors=True, NotifyOnValidationError=True 但未显示验证。

这是我的用户控件的 XAML(除了依赖属性声明之外没有其他代码隐藏逻辑):

<UserControl.Resources>
    <!-- Converters -->
    <local:ValidationBooleanToImageConverter x:Key="ValidationBooleanToImageConverter"/>
    <local:ValidationErrorToStringConverter x:Key="ValidationErrorToStringConverter"/>
    <local:DataTypeToVisibilityConverter DataType="Date" x:Key="DateDataTypeToVisibilityConverter"/>
    <local:DataTypeToVisibilityConverter DataType="Numeric" x:Key="NumericDataTypeToVisibilityConverter"/>
    <local:DataTypeToVisibilityConverter DataType="Enumeration" x:Key="EnumerationDataTypeToVisibilityConverter"/>
    <local:DateToStringConverter x:Key="DateToStringConverter"/>
    <!-- Styles -->
    <Style TargetType="{x:Type TextBox}">
        <Style.Triggers>
            <Trigger Property="Validation.HasError" Value="True">
                <Setter Property="ToolTip"
                        Value="{Binding RelativeSource={RelativeSource Self}, Path=(Validation.Errors).CurrentItem, Converter={StaticResource ResourceKey=ValidationErrorToStringConverter}}"/>
            </Trigger>
        </Style.Triggers>
    </Style>
</UserControl.Resources>
<Grid>
    <Grid.ColumnDefinitions>
        <ColumnDefinition/>
        <ColumnDefinition Width="16"/>
    </Grid.ColumnDefinitions>
    <toolkit:DatePicker Height="25" Margin="0,0,5,0" Visibility="{Binding Path=DataType, ElementName=UserControl, Converter={StaticResource ResourceKey=DateDataTypeToVisibilityConverter}}" SelectedDate="{Binding Path=Value, ElementName=UserControl, Converter={StaticResource ResourceKey=DateToStringConverter}}"/>
    <ComboBox Height="25" Margin="0,0,5,0" Visibility="{Binding Path=DataType, ElementName=UserControl, Converter={StaticResource ResourceKey=EnumerationDataTypeToVisibilityConverter}}" SelectedItem="{Binding Path=Value, ElementName=UserControl, Mode=TwoWay}" ItemsSource="{Binding Path=Items, ElementName=UserControl}" />
    <TextBox x:Name="_txtValue" Height="25" Margin="0,0,5,0" Visibility="{Binding Path=DataType, ElementName=UserControl, Converter={StaticResource ResourceKey=NumericDataTypeToVisibilityConverter}}" Text="{Binding Path=Value, ElementName=UserControl, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged, ValidatesOnDataErrors=True, NotifyOnValidationError=True}"/>
    <Image Grid.Column="2" Grid.Row="0" Source="{Binding ElementName=_txtValue, Path=(Validation.HasError), Converter={StaticResource ResourceKey=ValidationBooleanToImageConverter} }" ToolTip="{Binding ElementName=_txtValue, Path=ToolTip}" Width="16" Height="16"/>
</Grid>

...而较大视图中的用户控件引用是...

<control:ValueEditorControl DataType="{Binding Path=ContextualSelectedTagDataType}" Items="{Binding Path=ContextualSelectedTagItems}" Value="{Binding Path=ContextualSelectedTagDataObjectValue, Mode=TwoWay}" Height="25" VerticalAlignment="Top"/>

谁能指出我正确的方向?

【问题讨论】:

  • 我认为您需要将 IDataErrorInfo 的实现与您绑定到的 VM 部分一起发布

标签: c# wpf validation data-binding mvvm


【解决方案1】:

您的虚拟机是否实现了INotifyPropertyChanged?即使您实现了IDataErrorInfo,如果 WPF 没有收到有关 VM 更改的通知,那么它也不会绑定到这些更改。

话虽如此,我会将您的 ToolTip 设置器更改为:

<Setter Property="ToolTip"
            Value="{Binding RelativeSource={RelativeSource Self}, 
                   Path=(Validation.Errors)[0].ErrorContent}"/>

如果你想要整个风格,我会推荐这个:

<Style TargetType="{x:Type TextBox}">
    <Setter Property="Validation.ErrorTemplate">
        <Setter.Value>
            <ControlTemplate>
                <AdornedElementPlaceholder Name="controlWithError" />
            </ControlTemplate>
        </Setter.Value>
    </Setter>
    <Style.Triggers>
        <Trigger Property="Validation.HasError" Value="true">
            <Setter Property="Background" Value="LightPink"/>
            <Setter Property="ToolTip"
            Value="{Binding RelativeSource={RelativeSource Self}, 
                   Path=(Validation.Errors)[0].ErrorContent}"/>
        </Trigger>
    </Style.Triggers>
</Style>

【讨论】:

  • 感谢您的回复,何塞。我使用了 Josh Smith 所描述的技术来“避免调试喷射”来进行本博文中描述的验证(在 (Validation.Errors)[0] 引发异常的情况下):joshsmithonwpf.wordpress.com/2008/10/08/… 回答您的问题:是的, VM 实现 INotifyPropertyChanged。
  • @toadflakz Josh Smiths 的解决方法似乎不再需要了。在 .Net 4.0 中,它适用于 (Validation.Errors)[0].ErrorContent,输出中没有错误消息。
  • 我在这里仍然使用 3.5 SP1。可能应该提到这一点 - 它肯定会引发异常。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-03-09
  • 1970-01-01
  • 2018-02-07
  • 2013-08-02
相关资源
最近更新 更多