Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/308.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何将RowValidationErrorTemplate动态添加到数据网格?_C#_Wpf_Wpfdatagrid - Fatal编程技术网

C# 如何将RowValidationErrorTemplate动态添加到数据网格?

C# 如何将RowValidationErrorTemplate动态添加到数据网格?,c#,wpf,wpfdatagrid,C#,Wpf,Wpfdatagrid,我想使用C代码(即不在XAML中)将RowValidationErrorTemplate添加到数据网格中。 相应的XAML: <DataGrid.RowValidationErrorTemplate> <ControlTemplate> <Grid Margin="0,-2,0,-2" ToolTip="{Binding RelativeSource={RelativeSource FindAncestor, A

我想使用C代码(即不在XAML中)将RowValidationErrorTemplate添加到数据网格中。 相应的XAML:

<DataGrid.RowValidationErrorTemplate>
    <ControlTemplate>
        <Grid Margin="0,-2,0,-2" 
              ToolTip="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type DataGridRow}}, Path=(Validation.Errors)[0].ErrorContent}">
            <Ellipse StrokeThickness="0" Fill="Red" Width="{TemplateBinding FontSize}" 
                     Height="{TemplateBinding FontSize}" />
            <TextBlock Text="!" FontSize="{TemplateBinding FontSize}" 
                       FontWeight="Bold" Foreground="White" HorizontalAlignment="Center" />
        </Grid>
    </ControlTemplate>
</DataGrid.RowValidationErrorTemplate>

如果你想知道这背后的原因,以下是我的情况:

  • 我有几个继承自.cs代码的用户控件
  • 每个UserControl都包含一个数据网格,该数据网格具有:RowValidationErrorTemplate、事件处理程序、验证方法等。。。等等

  • 我将EventHandler移动到基类,现在我正在寻找将验证代码的最后一部分移动到基类的方法。

    您可以使用
    XamlReader.Parse
    方法动态创建
    ControlTemplate

    string xaml = "<ControlTemplate xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\" xmlns:x=\"http://schemas.microsoft.com/winfx/2006/xaml\"><Grid Margin=\"0,-2,0,-2\" ToolTip=\"{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type DataGridRow}}, Path=(Validation.Errors)[0].ErrorContent}\"><Ellipse StrokeThickness=\"0\" Fill=\"Red\" Width=\"{TemplateBinding FontSize}\" Height=\"{TemplateBinding FontSize}\" /><TextBlock Text=\"!\" FontSize=\"{TemplateBinding FontSize}\" FontWeight=\"Bold\" Foreground=\"White\" HorizontalAlignment=\"Center\" /></Grid></ControlTemplate>";
    dataGrid.RowValidationErrorTemplate = System.Windows.Markup.XamlReader.Parse(xaml) as ControlTemplate;
    
    string xaml=”“;
    dataGrid.RowValidationErrorTemplate=System.Windows.Markup.XamlReader.Parse(xaml)作为控制模板;
    
    为什么不创建您自己的从DataGrid继承的控件?@Isma,您是说XAML继承吗?这是一个非常复杂的话题,我尽量避免。这就是为什么我的UserControls继承自.cs代码。非常感谢。编辑控制模板的唯一方法是使用XAML格式吗?是否没有与XAML对应的类和属性?是的,有FrameworkElementFactory,但使用它是一种不推荐的方式,可以按照MSDN上的说明以编程方式创建模板:谢谢。他们说“推荐的以编程方式创建模板的方法是使用XamlReader类的load方法从字符串或内存流中加载XAML。”