我有两个属性相同的TextBox。例如:
<!-- TextBox1 -->
<TextBox Foreground="Red"
Style="{StaticResource MaterialTextBox}"
materialDesign:HintAssist.Foreground="Blue"
materialDesign:HintAssist.HintOpacity="100"
materialDesign:TextFieldAssist.UnderlineBrush="Green">
<materialDesign:HintAssist.Hint>
<TextBlock Foreground="{DynamicResource Lime}"
Text="SomeHint1" />
</materialDesign:HintAssist.Hint>
</TextBox>
<!-- TextBox2 -->
<TextBox Foreground="Red"
Style="{StaticResource MaterialTextBox}"
materialDesign:HintAssist.Foreground="Blue"
materialDesign:HintAssist.HintOpacity="100"
materialDesign:TextFieldAssist.UnderlineBrush="Green">
<materialDesign:HintAssist.Hint>
<TextBlock Foreground="{DynamicResource Lime}"
Text="SomeHint2" />
</materialDesign:HintAssist.Hint>
</TextBox>
请注意,唯一的区别是MaterialDesign:HintAssist.Hint
属性的"SomeHint1"
和"SomeHint2"
字符串。
所以我想我可以为它做一个样式:
<Style TargetType="TextBox" x:Key="TextBoxWithMaterialHintStyle" BasedOn="{StaticResource MaterialTextBox}">
<Setter Property="Foreground" Value="Red" />
<Setter Property="materialDesign:HintAssist.Foreground" Value="Blue" />
<Setter Property="materialDesign:HintAssist.HintOpacity" Value="100" />
<Setter Property="materialDesign:TextFieldAssist.UnderlineBrush" Value="Green" />
<Setter Property="materialDesign:HintAssist.Hint">
<Setter.Value>
<TextBlock Foreground="{DynamicResource Blue}"
Text="???" />
</Setter.Value>
</Setter>
</Style>
请注意,在我的样式中,TextBlock的Text
属性是"???"
我不知道如何将"SomeHint1"
或"SomeHint2"
传递给Style,并进一步传递给TextBlock的Text
属性。
有解决办法吗?
您也可以将DynamicResource
用于Text
<Setter.Value>
<TextBlock Foreground="{DynamicResource Blue}" Text="{DynamicResource hintStr}"/>
</Setter.Value>
然后只是
<TextBox ...>
<TextBox.Resources>
<Sys:String x:Key="hintStr" xmlns:Sys="clr-namespace:System;assembly=mscorlib">Hint1</Sys:String>
</TextBox.Resources>
</TextBox>
您可以将它放在ItemsControl中并绑定字符串列表。
例如:
<ItemsControl ItemsSource="{Binding Hints}">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<StackPanel Orientation="Vertical"/>
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<ItemsControl.ItemTemplate>
<TextBox Foreground="Red"
Style="{StaticResource MaterialTextBox}"
materialDesign:HintAssist.Foreground="Blue"
materialDesign:HintAssist.HintOpacity="100"
materialDesign:TextFieldAssist.UnderlineBrush="Green">
<materialDesign:HintAssist.Hint>
<TextBlock Foreground="{DynamicResource Lime}"
Text="{Binding}" />
</materialDesign:HintAssist.Hint>
</TextBox>
</ItemsControl.ItemTemplate>
</ItemsControl>
在您的ViewModel中可以是这样的属性:
public string[] Hints
{
get { return new[] {"SomeHint1", "SomeHint2"}; }
}