自定义控件在两种风格之间切换
我正在制作一个自定义控件,它有两种截然不同的样式需求。一种用于基本外观,另一种用于更高级的外观。
我的控件包含以下枚举的依赖属性:
public enum ControlTypes
{
Basic,
Advanced
}
我在 generic.xaml 中创建了两种样式(具有非常不同的模板),并为每个样式提供了一个键。
在枚举属性的更改处理程序中,我试图找到样式并设置正确的样式。
private static void OnControlTypePropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
var myCustomControl = (MyCustomControl)d;
var basicControlStyle = Application.Current.TryFindResource("BasicControlStyle") as Style;
var advancedControlStyle = Application.Current.TryFindResource("AdvancedControlStyle") as Style;
if (myCustomControl.ControlType == ControlTypes.Basic)
myCustomControl.Style = basicControlStyle;
else if (myCustomControl.ControlType == ControlTypes.Advanced)
myCustomControl.Style = advancedControlStyle;
}
这两种样式始终为空。我不确定如何从 generic.xaml 中获取样式。或者有更好的方法来交换我的风格吗?
I'm making a custom control which has two very different styling needs. One for a basic look, and another for a more advanced look.
My control contains a dependency property for the following enum:
public enum ControlTypes
{
Basic,
Advanced
}
I created two styles in the generic.xaml (with very different templates), and gave each a key.
Inside the change handler for the enum property I'm trying to find the styles and set the correct one.
private static void OnControlTypePropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
var myCustomControl = (MyCustomControl)d;
var basicControlStyle = Application.Current.TryFindResource("BasicControlStyle") as Style;
var advancedControlStyle = Application.Current.TryFindResource("AdvancedControlStyle") as Style;
if (myCustomControl.ControlType == ControlTypes.Basic)
myCustomControl.Style = basicControlStyle;
else if (myCustomControl.ControlType == ControlTypes.Advanced)
myCustomControl.Style = advancedControlStyle;
}
The two styles are always null. I'm not sure how to get the styles from inside the generic.xaml. Or is there a better way to swap my styles?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
删除 OnControlTypePropertyChanged 中的代码并将类似的内容放入 XAML 中。请注意,我已绑定到一个名为 IsAdvanced 的属性,因为它更易于测试,但您可以通过更改 {x:Static namespace:nameofyourenum.Value} 的“True”来绑定到枚举。
请注意,这仍然给使用您的程序员提供了帮助。控制能力完全覆盖控制模板并做自己想做的事。您原来的方法不允许这样做。
Delete the code in OnControlTypePropertyChanged and put something like this in your XAML. Note that I have bound to a property called IsAdvanced because it was simpler for testing but you can bind to an enum by changing the "True" for {x:Static namespace:nameofyourenum.Value}
Note that this still give the programmer who uses your control the ability to completely override the control template and do what they want. Your original approach didn't allow this.