gpt4 book ai didi

wpf - WPF 样式的绑定(bind)

转载 作者:行者123 更新时间:2023-12-03 08:21:40 25 4
gpt4 key购买 nike

我正在尝试创建一个自定义控件 - 一个按钮 - 根据数据上下文中属性的值,它将应用多种样式。

我在想的是使用类似的东西:

<Button Style="{Binding Path=ButtonStyleProperty, Converter={StaticResource styleConverter}}" Text="{Binding Path=TextProp}" />

在代码中... 实现一个 IValueConverter,它执行类似于 ConvertTo 中的以下代码的操作方法:
switch(value as ValueEnums)
{
case ValueEnums.Enum1:
FindResource("Enum1ButtonStyle") as Style;
break;

... and so on.
}

但是,我不完全确定如何拉出样式对象,即使这是可能的......

同时我正在做的是处理 DataContextChanged事件,然后将处理程序附加到 PropertyChanged对象绑定(bind)到按钮的事件 - 然后在其中运行 switch 语句。

它不是很完美,但在我找到更好的解决方案之前,这似乎是我必须使用的。

最佳答案

查看型号

private Style _dynamicStyle = (Style)Application.Current.FindResource("Style1");
public Style DynamicStyle
{
get { return _dynamicStyle; }
set
{
_dynamicStyle = value;
OnPropertyChanged("DynamicStyle");
}

}

public event PropertyChangedEventHandler PropertyChanged;

private void OnPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}

在您的 ViewModel 中实现一个属性,然后在您想要的任何位置动态更改样式,如下所示。
DynamicStyle=(Style)Application.Current.FindResource("Style2");// you can place this code where the action get fired

查看

然后设置 数据上下文 值,然后在您的 View 中实现以下代码
    <Button Style="{Binding DynamicStyle,Mode=TwoWay}"/>

关于wpf - WPF 样式的绑定(bind),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/410579/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com