无法在触发器 wpf 中设置样式



我想在选中切换按钮时更改样式

<ToggleButton.Style>
                <Style TargetType="ToggleButton" BasedOn="{StaticResource ToggleButtonPrimary}">
                    <Style.Triggers>
                        <DataTrigger Binding="{Binding ElementName=ButtonNude, Path=IsChecked}" Value="True">
                            <Setter Property="Style" Value="{StaticResource ToggleButtonDanger}"/>
                        </DataTrigger>
                    </Style.Triggers>
                </Style>
            </ToggleButton.Style>

但我的代码不起作用并且应用程序崩溃

正如 @clemens 所建议的,正确的方法是拥有模板并与 TargetName 一起应用于controlTemplate

还有一种(可能很丑陋)的方法:

展出:

    <StackPanel>
            <StackPanel.Resources>
                <local:Myconverter x:Key="MyConverter" />
                <Style TargetType="ToggleButton" x:Key="ToggleButtonPrimary">
                    <Setter Property="Background" Value="blue" />
                </Style>
                <Style TargetType="ToggleButton" x:Key="ToggleButtonDanger">
                    <Setter Property="Background" Value="Red" />
                </Style>
            </StackPanel.Resources>
            <CheckBox Margin="20" x:Name="chk" />
            <ToggleButton Width="100" Height="100" >
                <ToggleButton.Style>
                    <MultiBinding Converter="{StaticResource MyConverter}">
                        <MultiBinding.Bindings>
                            <Binding ElementName="chk" Path="IsChecked"/>                            
                            <Binding RelativeSource="{RelativeSource AncestorType=StackPanel}"/>                            
                        </MultiBinding.Bindings>
                    </MultiBinding>
                </ToggleButton.Style>            
            </ToggleButton>
        </StackPanel>

转炉:

    public class Myconverter : IMultiValueConverter
    {
        public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
        {
            if ((bool)values[0])
            {
                return (values[1] as FrameworkElement).Resources["ToggleButtonDanger"];
            }
            else
                return (values[1] as FrameworkElement).Resources["ToggleButtonPrimary"];            
        }

        public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
        {
            throw new NotImplementedException();
        }
    }

希望有帮助。

相关内容

  • 没有找到相关文章