【发布时间】:2015-07-24 16:58:10
【问题描述】:
WPF 和 XAML 新手在这里....
我需要将 XAML 代码中的 WPF Trigger 或 DataTrigger 绑定到 XAML 控件类以外的类中的某些 C# 代码中。这非常令人沮丧,因为我读过的所有 28,000 篇教程都只给出了 Trigger 或 DataTrigger 的一个简单示例,其中涉及 已经存在的属性(例如 MouseOver),没有一个给出示例如何将它与您自己的 C# 代码联系起来。
我有一个显示各种报告类型的屏幕。所有报告类型的 XAML 都是相同的,除了诊断报告,我的要求是 DataGrid 单元格配置为TextBlock.TextAlignment="Left",而所有其他报告(即默认值)应为TextBlock.TextAlignment="Center"。 (还有一些其他差异;为简洁起见,我只想说这是唯一的差异。)我真的不想复制整个 XAML 来特殊情况下的诊断报告,因为其中 99% 是与其他报告相同。
要使用触发器,我想也许我需要我的类从 DependencyObject 继承,以便我可以在其中定义 DependencyProperty(作为 WPF 新手,我意识到我可能会说一些非常奇怪的事情)。所以在我的 C# 代码中,我有一个类...
namespace MyApplication
{
public enum SelectedReportType
{
EquipSummary,
EventSummary,
UserSummary,
DiagSummary
}
public sealed class ReportSettingsData : DependencyObject
{
private static ReportSettingsData _instance; // singleton
static ReportSettingsData() { new ReportSettingsData(); }
private ReportSettingsData() // private because it's a singleton
{
if (_instance == null) // only true when called via the static constructor
_instance = this; // set here instead of the static constructor so it's available immediately
SelectedReport = SelectedReportType.EquipSummary; // set the initial/default report type
}
public static ReportSettingsData Instance
{
get { return _instance; }
}
public static SelectedReportType SelectedReport
{
get { return (SelectedReportType)Instance.GetValue(SelectedReportProperty); }
set { Instance.SetValue(SelectedReportProperty, value); }
}
public static readonly DependencyProperty SelectedReportProperty =
DependencyProperty.Register("SelectedReport", typeof(SelectedReportType), typeof(ReportSettingsData));
}
}
所以在我的 XAML 文件中,我使用了 Trigger 和 DataTrigger 的各种咒语,但不知道如何使它工作。在每种情况下,诊断报告都具有与其他报告相同的默认特征。
<my:HeaderVisual x:Class="MyApplication.ReportsView"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:my="clr-namespace:MyApplication">
<DataGrid Name="_dgReport"
ColumnWidth="Auto"
CanUserAddRows="False"
VerticalScrollBarVisibility="Auto"
HorizontalScrollBarVisibility="Auto"
ItemsSource="{Binding}"
IsReadOnly="True">
<DataGrid.Resources>
<Style TargetType="DataGridCell">
<Setter Property="TextBlock.TextAlignment" Value="Center"></Setter>
<Style.Triggers>
<!-- Override some property settings for Diagnostics reports... -->
<!--
<DataTrigger Binding="{Binding my:ReportSettingsData.SelectedReport}" Value="DiagSummary">
<DataTrigger Binding="{Binding Path=my:ReportSettingsData.SelectedReport}" Value="DiagSummary">
-->
<Trigger Property="my:ReportSettingsData.SelectedReport" Value="DiagSummary">
<Setter Property="TextBlock.TextAlignment" Value="Left"></Setter>
</Trigger>
</Style.Triggers>
</Style>
</DataGrid.Resources>
</DataGrid>
</my:HeaderVisual>
我怎样才能让我的Trigger 在ReportSettingsData.SelectedReport == SelectedReportType.DiagSummary 时触发?
【问题讨论】: