2010-03-25 59 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