【发布时间】:2017-03-30 02:19:02
【问题描述】:
我在 DataTemplates.xaml
中有以下 DataTemplate<DataTemplate DataType="{x:Type local:ExcelReportVM}">
<local:ExcelReport DoubleClickHandler="{Binding}">
<local:ExcelReport.RowColorConverter>
<local:ReportRowColorConverter/>
</local:ExcelReport.RowColorConverter>
</local:ExcelReport>
</DataTemplate>
我通过以下 App.xaml 定义确保此 DataTemplate 在应用程序范围内可用:
<Application x:Class="WpfApplication1.App"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:WpfApplication1"
StartupUri="MainWindow.xaml">
<Application.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="DataTemplates.xaml"/>
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
</Application.Resources>
</Application>
这是我的控制ExcelReport.xaml:
<UserControl x:Class="WpfApplication1.ExcelReport"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
....
xmlns:syncfusion="http://schemas.syncfusion.com/wpf"
d:DesignHeight="300" d:DesignWidth="300">
<UserControl.Resources>
<DataTemplate x:Key="HeaderTemplate">
<TextBlock TextAlignment="Center" Text="{Binding .}" TextWrapping="WrapWithOverflow" />
</DataTemplate>
</UserControl.Resources>
<UserControl.DataContext>
<local:ExcelReportVM/>
</UserControl.DataContext>
<syncfusion:SfDataGrid ItemsSource="{Binding Entries}" x:Name="grid" Background="White"
HeaderTemplate="{StaticResource HeaderTemplate}"
SelectedItem="{Binding SelectedItem, RelativeSource={RelativeSource AncestorType=UserControl}}">
</syncfusion:SfDataGrid>
</UserControl>
我的代码:ExcelReport.xaml.cs
public partial class ExcelReport : UserControl
{
public static readonly DependencyProperty RowColorConverterProperty = DependencyProperty.Register(
"RowColorConverter",
typeof(IValueConverter),
typeof(ExcelReport),
new FrameworkPropertyMetadata(new PropertyChangedCallback(OnRowColorConverterChanged))
);
public IValueConverter RowColorConverter
{
get { return (IValueConverter)GetValue(RowColorConverterProperty); }
set { SetValue(RowColorConverterProperty, value); }
}
public ExcelReport()
{
InitializeComponent();
this.Loaded += OnLoaded;
}
private void OnLoaded(object sender, RoutedEventArgs e)
{
Debug.Assert(DataContext.GetType()==typeof(ExcelReportVM)); //DataContext is correct
Debug.Assert(RowColorConverter!=null); //but this is null
}
}
我不知道为什么我可以成功绑定DataContext,但是我定义的<DataTemplate DataType="{x:Type local:ExcelReportVM}">没有被使用,我以为ExcelReport.xaml可以访问DataTemplates.xaml中的所有内容?
注意:输出窗口中没有错误,代码中没有任何地方抛出异常。
【问题讨论】:
-
运行此程序时,您的输出窗口是否有任何错误?
-
@JBrooks,不,完全没有错误。
-
你在哪里使用这个
<DataTemplate DataType="{x:Type local:ExcelReportVM}">?我在您当前的代码中看不到这一点。 -
@AnjumSKhan,它在代码块的第一个
DataTemplates.xaml里面 -
@Graviton 我是说你在哪里使用它?
标签: c# wpf xaml datatemplate