[英]WPF UserControl: Client-side validation of TargetType for custom styles?
我有一個用於多種用途的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}" />
我想知道,是否有一種方法可以驗證StaticResource
樣式的TargetTypes
,以便分別將它們定位到stackpanel或button?
例如,樣式ExpandingButtonGridExpandButtonStyle
可以定位到DockPanel
,從而在運行時導致XAML解析異常。
更新-有關依賴對象的摘要和更新
我剛剛弄清楚什么是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);
}
}
當然可以。 您可以在設置器中驗證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;
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.