DataGrid列验证错误模板

时间:2016-12-15 10:46:47

标签: .net wpf validation xaml datagrid

我有DataGrid DataGridTextColumn,需要进行一些验证。

<DataGridTextColumn Header="Key" Width="100">
<DataGridTextColumn.Binding>
    <Binding Path="Key">
        <Binding.ValidationRules>
            <local:DistinctValidation/>
        </Binding.ValidationRules>
    </Binding>
</DataGridTextColumn.Binding>

DataGrid本身没有应用任何样式,但DataGridTextColumn包含以下内容:

<Style TargetType="{x:Type DataGridTextColumn}">
<Setter Property="Validation.ErrorTemplate">
    <Setter.Value>
        <ControlTemplate>
            <StackPanel>
                <AdornedElementPlaceholder x:Name="placeholder" />
                <Popup HorizontalAlignment="Left" PopupAnimation="Fade" Placement="Bottom" IsOpen="true">
                    <TextBlock Text="{Binding [0].ErrorContent}"/>
                </Popup>
            </StackPanel>
        </ControlTemplate>
    </Setter.Value>
</Setter>

为简单起见,我尝试将Popup上的IsOpen始终设置为true。然而,弹出窗口从未出现过 Popup

1 个答案:

答案 0 :(得分:1)

您应该为要应用的模板的列的EditingElementStyle设置Validation.ErrorTemplate属性:

<DataGridTextColumn Binding="{Binding Test}">
  <DataGridTextColumn.EditingElementStyle>
    <Style TargetType="TextBox">
        <Setter Property="Validation.ErrorTemplate">
            <Setter.Value>
                <ControlTemplate>
                    <StackPanel>
                        <AdornedElementPlaceholder x:Name="placeholder" />
                        <Popup HorizontalAlignment="Left" PopupAnimation="Fade" Placement="Bottom" IsOpen="true">
                            <Grid Background="White">
                                <TextBlock Text="{Binding [0].ErrorContent}"/>
                            </Grid>
                        </Popup>
                    </StackPanel>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>
  </DataGridTextColumn.EditingElementStyle>
</DataGridTextColumn>