我正在显示几个测试的结果。每个测试有2个变量,显示结果的文本和颜色随两者而变化。我有这个工作,但是有很多重复的MultiBinding正在进行,我想看看是否有办法使用Style来简化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,以便我可以更轻松地将MultiBindings应用于TextBlocks。每个中唯一的区别是我在Binding Path值中指定的测试。我的目标是:
<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 --> />
这可能与此类似吗?
答案 0 :(得分:14)
你可以这样做:
<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使用。