【发布时间】:2016-09-07 07:14:40
【问题描述】:
我喜欢将我的一些自定义控件分离到一个 dll 中。
假设我有以下示例控件:
MyControl.cs
namespace MyControlsNs {
public class MyControl : ContentControl {
public static DependencyProperty IsGreatProperty =
DependencyProperty.Register("IsGreat",
typeof (bool),
typeof (MyControl),
new PropertyMetadata(true));
public bool IsGreat {
get { return (bool) GetValue(IsGreatProperty); }
set { SetValue(IsGreatProperty, value); }
}
}
}
MyControl.xaml
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:controls="clr-namespace:MyControlsNs">
<Style x:Key="MyControl" TargetType="controls:MyControl">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate>
<CheckBox IsChecked="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=IsGreat}" />
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</ResourceDictionary>
如果我想使用 MyControl,我实际上会执行以下操作:
<UserControl x:Class="MyMainViewClass"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:controls="clr-namespace:MyControlsNs">
<UserControl.Resources>
<ResourceDictionary Source="MyControl.xaml" />
</UserControl.Resources>
<controls:MyControl IsGreat="true" Style="{StaticResource MyControl}" />
</UserControl>
当我在 MyMainViewClass 中使用它时,我的目标是保持 RD 和 Style 的定义;像这样:
<UserControl x:Class="MyMainViewClass"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:controls="clr-namespace:MyControlsLib.MyControlsNs;assembly=MyControlsLib">
<controls:MyControl IsGreat="true" />
</UserControl>
如何为 MyControl 定义默认样式? 我找到了这个线程Creating default style,但集成对我不起作用:
static MyControl() {
DefaultStyleKeyProperty.OverrideMetadata(typeof(MyControl), new FrameworkPropertyMetadata(typeof(MyControl)));
}
【问题讨论】: