我有UserControl
用于多用途。
为了简单起见,我先向您展示控件:
<UserControl x:Class="CompetitionAgent.View.UserControls.ExpandingButtonGrid"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
mc:Ignorable="d" d:DesignWidth="200" d:DesignHeight="200"
Margin="0" Padding="0" Width="Auto" Height="Auto" >
<StackPanel Name="stpBody" Style="{Binding Style}">
<Button x:Name="btnExpander" Content="{Binding ExpanderButtonText}"
Style="{Binding ExpandButtonStyle}"
HorizontalAlignment="Center" Click="btnExpander_Click"
Height="25" Width="Auto" />
<StackPanel x:Name="stpButtons" Orientation="Horizontal"
Style="{Binding PanelStyle}"
Margin="0">
</StackPanel>
</StackPanel>
</UserControl>
控件stpBody
,stpButtons
和btnExpander
都有DataContext
绑定的样式。字段看起来像这样:
#region body styles
public Style Style { get; set; }
public Style ExpandButtonStyle { get; set; }
#endregion body styles
#region button pannel styles
public Style PanelStyle { get; set; }
public Style ButtonStyle { get; set; }
#endregion button pannel styles
因此,当在另一个窗口中使用此UserControl
时,它看起来会像这样:
<UserControls:ExpandingButtonGrid x:Name="ebgSchemeManager"
Style="{StaticResource ExpandingButtonGridStyle}"
PanelStyle="{StaticResource ExpandingButtonGridPanelStyle}"
ExpandButtonStyle="{StaticResource ExpandingButtonGridExpandButtonStyle}" />
我想知道,有没有办法验证TargetTypes
样式的StaticResource
,以便他们分别需要定位堆栈面板或按钮?
例如,样式ExpandingButtonGridExpandButtonStyle
可以定位DockPanel
,从而在运行时导致XAML解析异常。
更新 - Depency对象的摘要和更新
我刚刚弄明白DepencyObjects
是什么(欢呼!)。
对于那些想知道的人,您需要注册该字段,以便可以动态地分配属性。
public static readonly DependencyProperty ExpandButtonStyleProperty =
DependencyProperty.Register("ExpandButtonStyle", typeof(Style), typeof(ExpandingButtonPanel));
public Style ExpandButtonStyle
{
get
{
return (Style)GetValue(ExpandButtonStyleProperty);
}
set
{
if (!typeof(Button).IsAssignableFrom(value.TargetType))
{
throw new ArgumentException("The target type is expected to be button");
}
SetValue(ExpandButtonStyleProperty, value);
}
}
答案 0 :(得分:1)
当然有。您可以验证设置器中的Style.TargetType
。这也将由WPF设计师检查。
例如:
private Style _buttonStyle;
public Style ButtonStyle
{
get
{
return _buttonStyle;
}
set
{
if (!typeof(Button).IsAssignableFrom(value.TargetType))
{
throw new ArgumentException("The target type is expected to be Button");
}
_buttonStyle = value;
}
}