我們可以通過IMultiValue轉換器更換整個風格。
對於您的要求,我想出了這個例子
public class StyleConverter : IMultiValueConverter
{
public object Convert(object[] values, Type targetType,
object parameter, CultureInfo culture)
{
if (values.Length < 1)
return Binding.DoNothing;
bool isCorrect = (bool)values[0];
bool isNotCorrect = (bool)values[1];
Style firstStyle = (Style)values[2];
Style secondStyle = (Style)values[3];
if (isCorrect)
return firstStyle;
if (isNotCorrect)
return secondStyle;
return Binding.DoNothing;
}
public object[] ConvertBack(object value, Type[] targetTypes,
object parameter, CultureInfo culture)
{
throw new NotSupportedException();
}
}
XAML
<Window x:Class="StackWpf.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:StackWpf"
Title="MainWindow" Name="window" Height="350" Width="525" >
<Window.Resources>
<ResourceDictionary>
<Style TargetType="Button" x:Key="WhiteStyle">
<Setter Property="Background" Value="White"/>
</Style>
<Style TargetType="Button" x:Key="BlueStyle">
<Setter Property="Background" Value="Blue"/>
</Style>
<local:StyleConverter x:Key="styleConverter"/>
</ResourceDictionary>
</Window.Resources>
<Grid>
<RadioButton Name="rbInfoCorrect" IsChecked="False"
GroupName="InfoQuestion" Margin="80,19,382,257">
<RadioButton.Content>
<TextBlock Text="Yes" Foreground="Black"/>
</RadioButton.Content>
</RadioButton>
<RadioButton Name="rbInfoNotCorrect" IsChecked="False"
GroupName="InfoQuestion" Margin="80,38,391,257">
<RadioButton.Content>
<TextBlock Text="No" Foreground="Black"/>
</RadioButton.Content>
</RadioButton>
<Button Content="Button" Margin="80,114,294,161">
<Button.Style>
<MultiBinding Converter="{StaticResource styleConverter}">
<Binding ElementName="rbInfoCorrect"
Path="IsChecked" />
<Binding ElementName="rbInfoNotCorrect"
Path="IsChecked" />
<Binding Source="{StaticResource WhiteStyle}" />
<Binding Source="{StaticResource BlueStyle}" />
</MultiBinding>
</Button.Style>
</Button>
</Grid>
</Window>
我已經使用這個好文章http://social.msdn.microsoft.com/Forums/vstudio/en-US/b25973bb-9e9c-4a99-8234-39a042e0a478/apply-styles-dynamically-to-buttons-in-xaml?forum=wpf早些時候,以解決我的問題。
感謝您的回覆,但我正在尋找一種方式來改變不僅僅是像漸變和其他東西的背景屬性,所以我想要一種方式來重用現有的樣式資源。 – Harish