我有一个文本框,它具有以下简单的XAML代码(不需要阅读 - 只是作为参考):
<TextBox Name="m_ctrlUserDeviceType" Style="{StaticResource textStyleTextBox}" Text="{Binding Source={x:Static api:MySettings.Instance}, Path=UserDeviceType, ValidatesOnExceptions=true, NotifyOnValidationError=true}" Validation.Error="TextBox_Error" MinHeight="25" Margin="4" VerticalAlignment="Top" MaxLength="23" VerticalContentAlignment="Center" HorizontalAlignment="Left" MinWidth="100"></TextBox>
为了完整起见,样式textStyleTextBox看起来像这样(再次强调,阅读此内容并非回答问题所必须):
<Style x:Key="textStyleTextBox" TargetType="TextBox">
<Setter Property="Foreground" Value="#333333" />
<Setter Property="VerticalAlignment" Value="Top" />
<Setter Property="MinHeight" Value="2" />
<Setter Property="MinWidth" Value="100" />
<Setter Property="Margin" Value="4" />
<Setter Property="MaxLength" Value="23" />
<Setter Property="VerticalContentAlignment" Value="Center" />
<Setter Property="HorizontalAlignment" Value="Left" />
<!-- <Setter Property="Binding Source" Value="{x:Static api:MySettings.Instance}"/>
<Setter Property="Binding ValidatesOnExceptions" Value="true" />
<Setter Property="Binding NotifyOnValidationError" Value="true" /> -->
<Style.Triggers>
<Trigger Property="Validation.HasError" Value="true">
<Setter Property="ToolTip" Value="{Binding RelativeSource={RelativeSource Self},
Path=(Validation.Errors)[0].ErrorContent}" />
</Trigger>
</Style.Triggers>
</Style>
我在样式中有很多东西(如MiHeight,Margin等),因为我有很多这些文本框,它们几乎完全相同。实际上,它们之间的共同点不仅仅是样式。绑定到MySettings类的详细信息几乎相同。唯一的区别是文本框绑定的特定属性是哪个。此外,我总是使用TextBox_Error进行Validation.Error。
有没有办法将绑定信息放在样式或数据模板中,以便我不必为每个文本框都输入它?
我需要能够为每个文本框分配单独的属性(Path),我想我还需要能够在未来添加某些与MySettings数据绑定无关的特定文本框时不使用任何属性。
是否有办法将TextBox_Error部分放在样式或DataTemplate中?对我来说,使用Setter Property似乎不起作用。
我一直在提到Data Template,因为根据阅读《Pro Silverlight 2 in C# 2008》的经验,答案可能与此有关。但是,我无法弄清楚它。我也尝试在“Style”中添加内容,正如您可以从该部分的注释中看到的那样。
谢谢,
戴夫