2010-03-25 60 views
0

是否有可能设置的SolidColorBrush的厚度方向性能。我问的原因是,我有一个的IValueConverter绑定到文本框边框BorderBrush属性和我动态设置文本框的颜色,的SolidColorBrush厚度财产

<Window x:Class="MyWindow" 
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:sys="clr-namespace:System;assembly=mscorlib" Width="600" Height="570"> 

<ResourceDictionary 
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"> 

    <Style TargetType="{x:Type TextBlock}" x:Key="Style1"> 
     <Setter Property="BorderBrush" Value="DarkGrey" /> 
     <Setter Property="BorderThickness" Value="1" /> 
    </Style> 

    <Style TargetType="{x:Type TextBlock}" x:Key="Style2"> 
     <Setter Property="BorderBrush" Value="Red" /> 
     <Setter Property="BorderThickness" Value="2" /> 
    </Style> 

</ResourceDictionary> 

回答

1

的BorderBrush属性只定义边框的颜色,设置厚度你将不得不设置BorderThickness属性。

这样做是设置样式属性的转换器来代替,这样你可以使用一个转换器来设置边框刷,厚度,你可能要修改任何其他属性,如字体的一种更好的方法颜色等

如果您在XAML资源字典中定义你的风格,你可以从你的转换器,像这样内加载...

public class TextboxStyleConverter : IValueConverter 
{ 
    public object Convert(
     object value, Type targetType, object parameter, 
     System.Globalization.CultureInfo culture) 
    { 
     if(some condition is true) 
      return (Style)Application.Current.FindResource("MyStyle1"); 
     else 
      return (Style)Application.Current.FindResource("MyStyle2"); 
    } 

    public object ConvertBack(object value, Type targetType, object parameter, 
     System.Globalization.CultureInfo culture) 
    { 
     throw new NotImplementedException(); 
    } 
} 

这样你可以定义你所需要的款式和负载从你的转换器类中的适当的一个。

来定义你的风格,最好的办法是资源字典内 - 这是你的解决方案中只是一个XAML文件。请参阅下面的例子...

<ResourceDictionary 
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"> 

    <Style TargetType="{x:Type TextBlock}" x:Key="Style1"> 
     <Setter Property="BorderBrush" Value="DarkGrey" /> 
     <Setter Property="BorderThickness" Value="1" /> 
    </Style> 

    <Style TargetType="{x:Type TextBlock}" x:Key="Style2"> 
     <Setter Property="BorderBrush" Value="Red" /> 
     <Setter Property="BorderThickness" Value="2" /> 
    </Style> 

</ResourceDictionary> 

如果你想保持你的ResourceDictionary在一个单独的文件,以便它可以通过多个Windows /用户控件可以很容易地引用,你需要把它列入你的Window.Resources/UserControl.Resources在要使用的每个xaml文件上。如果您包含多个资源,则需要使用该标记(请参阅下文),否则只需将该部分忽略并将ResourceDictionary包含在标记中。

<Window> 
    <Window.Resources> 
     <ResourceDictionary.MergedDictionaries> 
      <ResourceDictionary Source="../ResourceDictionary1.xaml" /> 
      <ResourceDictionary Source="../ResourceDictionary2.xaml" /> 
     </ResourceDictionary.MergedDictionaries> 
    </ResourceDictionary> 
</Window.Resources> 
+0

你能告诉我怎么用IValueConverter做这件事吗? – developer 2010-03-25 15:04:48

+0

请参阅如何访问样式... – TabbyCool 2010-03-25 16:53:38

+0

我想我的贴转换器的代码编辑答案。你可以编辑它,并告诉我如何使用样式添加边框的厚度和颜色。我是wpf的新手,所以如果你可以请求帮助。 – developer 2010-03-25 17:17:48