我正在显示几个测试的结果。每个测试有 2 个变量,显示结果的文本和颜色因变量而异。我有这个工作,但是有很多重复的多重绑定正在进行,我想看看是否有办法使用样式来简化 XAML。
以下是我的代码外观的简化外观:
//TestResults.cs excerpt
public class TestResults
{
private Test1Result test1 = new Test1Result();
public Test1Result Test1 { get { return test1; } }
private Test2Result test2 = new Test2Result();
public Test2Result Test2 { get { return test2; } }
}
//TestCtrl.xaml.cs excerpt
public class TestCtrl : UserControl
{
private TestResults results = new TestResults();
public TestResults Results { get { return results; } }
}
<!-- TestCtrl.xaml excerpt -->
<UserControl x:Class="Tester.TestCtrl" x:Name="TestResultsCtrl" ...>
<!-- lots of stuff -->
<TextBlock Grid.Row="6">
<TextBlock.Text>
<MultiBinding Converter="{StaticResource TestToTextConverter}" >
<Binding Path="Results.Test1.Temperature" ElementName="TestResultsCtrl" />
<Binding Path="Results.Test1.Time" ElementName="TestResultsCtrl" />
</MultiBinding>
</TextBlock.Text>
<TextBlock.Foreground>
<MultiBinding Converter="{StaticResource TestToBrushConverter}">
<Binding Path="Results.Test1.Temperature" ElementName="TestResultsCtrl" />
<Binding Path="Results.Test1.Time" ElementName="TestResultsCtrl" />
</MultiBinding>
</TextBlock.Foreground>
</TextBlock>
<TextBlock Grid.Row="7">
<TextBlock.Text>
<MultiBinding Converter="{StaticResource TestToTextConverter}" >
<Binding Path="Results.Test2.Temperature" ElementName="TestResultsCtrl" />
<Binding Path="Results.Test2.Time" ElementName="TestResultsCtrl" />
</MultiBinding>
</TextBlock.Text>
<TextBlock.Foreground>
<MultiBinding Converter="{StaticResource TestToBrushConverter}">
<Binding Path="Results.Test2.Temperature" ElementName="TestResultsCtrl" />
<Binding Path="Results.Test2.Time" ElementName="TestResultsCtrl" />
</MultiBinding>
</TextBlock.Foreground>
</TextBlock>
<!-- lots more repetitions here -->
我想定义一个样式,以便我可以更轻松地将多重绑定应用于文本块。每个测试的唯一区别是我在绑定路径值中指定的测试。我的目标是这样的:
<Style x:Key="TestResultsStyle" TargetType="{x:Type TextBlock}">
<!-- do binding stuff here -->
</Style>
<TextBlock Grid.Row="6"
Style="{StaticResource TestResultsStyle}" <!--set Test1 path here --> />
<TextBlock Grid.Row="7"
Style="{StaticResource TestResultsStyle}" <!--set Test2 path here --> />
有没有类似的事情可能?
你可以做这样的事情:
<Style x:Key="TestResultsStyle" TargetType="{x:Type TextBlock}">
<Setter Property="Text">
<Setter.Value>
<MultiBinding Converter="{StaticResource TestToTextConverter}" >
<Binding Path="Temperature" />
<Binding Path="Time" />
</MultiBinding>
</Setter.Value>
</Setter>
<!-- Same for Foreground -->
</Style>
<TextBlock Grid.Row="6"
DataContext="{Binding ElementName=TestResultsCtrl, Path=Results.Test1}"
Style="{StaticResource TestResultsStyle}" />
<TextBlock Grid.Row="7"
DataContext="{Binding ElementName=TestResultsCtrl, Path=Results.Test2}"
Style="{StaticResource TestResultsStyle}" />
在这里,您将"Test"作为默认绑定上下文传递,该上下文由 Style 使用。