排序的,首先你的風格之前定義的轉換器:
<local:ColorConverter x:Key="colorConverter" />
然後你可以用它們作爲你的風格StaticResources:
<Setter Property="BorderBrush" Value="{Binding Converter={StaticResource colorConverter}}" />
完整的示例
C#:
using System;
using System.Windows;
using System.Windows.Data;
using System.Windows.Media;
namespace WpfApplication1
{
/// <summary>
/// Interaction logic for Window1.xaml
/// </summary>
public partial class Window1 : Window
{
public Window1()
{
InitializeComponent();
}
}
// The converter
public class ColorConverter : IValueConverter
{
#region IValueConverter Members
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
return Brushes.Red;
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotImplementedException();
}
#endregion
}
}
XAML:
<Window x:Class="WpfApplication1.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:WpfApplication1"
Title="Window1" Height="300" Width="354">
<Window.Resources>
<local:ColorConverter x:Key="colorConverter" />
<Style TargetType="{x:Type Button}">
<Setter Property="Background" Value="{Binding Converter={StaticResource colorConverter}}" />
</Style>
</Window.Resources>
<Grid>
<Button Margin="8" Content="A button" HorizontalAlignment="Center" VerticalAlignment="Center" />
</Grid>
</Window>
順便說一句,現在我想想,不知道你是否簡化你的代碼,但你實際上並不需要一個轉換器。您可以設置的SolidColorBrush而不是轉換器的(除非你做轉爐一些代碼),這樣的事情:
<Window.Resources>
<SolidColorBrush Color="Red" x:Key="redSolidColorBrush" />
<SolidColorBrush Color="White" x:Key="whiteSolidColorBrush" />
<Style TargetType="{x:Type Button}">
<Setter Property="Background" Value="{StaticResource redSolidColorBrush}" />
<Setter Property="Foreground" Value="{StaticResource whiteSolidColorBrush}" />
</Style>
</Window.Resources>
<Grid>
<Button Margin="8" Content="A button" HorizontalAlignment="Center" VerticalAlignment="Center" />
</Grid>
呀,應該工作..但我得到每個屬性如下:「WpfGridtest。 ColorConverter'對屬性'Background'來說不是一個有效的值......用以前的記法工作得很好......錯誤消息中的namespace.type是正確的類......它返回SolidColorBrush – 2010-06-21 19:21:42
我將添加一個完整的示例,我2分鐘。 – Carlo 2010-06-21 19:36:28
@Sonic Soul:讓我知道,如果這可以幫助你更多,完美的工作在我身邊。謝謝。 – Carlo 2010-06-21 19:40:03