我剛爲自定義按鈕創建了一個DependencyProperty
。 該物業被稱爲IsChecked
。 如果IsChecked == true
我的按鈕應改變其背景顏色,並保持這種顏色,直到IsChecked == false
。通過XAML訪問`DependencyProperty`並評估它?
這裏是我的DependencyProperty
:
public static readonly DependencyProperty IsCheckedProperty = DependencyProperty.Register("IsChecked", typeof(bool), typeof(MainMenuButton), new PropertyMetadata(false));
public bool IsChecked
{
get { return (bool)GetValue(IsCheckedProperty); }
set { SetValue(IsCheckedProperty, value); }
}
接下來,我有一個ControlTemplate
此按鈕:
<ResourceDictionary
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<ControlTemplate x:Key="MainMenuButtonStyle" TargetType="{x:Type UserControl}">
<ControlTemplate.Resources>
/* Some storyboards */
</ControlTemplate.Resources>
<Grid x:Name="grid">
<Grid.Background>
<SolidColorBrush Color="{DynamicResource MainUI_MainMenuButtonBackground}"/>
</Grid.Background>
</Grid>
<ControlTemplate.Triggers>
/* Some triggers */
</ControlTemplate.Triggers>
</ControlTemplate>
我現在的問題是我怎麼能訪問IsChecked
和基於當前它的價值改變了grid
的背景?之前沒有做過,只是前一段時間嘗試過,完全失敗。
感謝提前:)
編輯: 這裏是UserControl
藏漢:
<UserControl
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
x:Class="IFCSMainInterface.MainMenuButton"
x:Name="UserControl"
d:DesignWidth="640" d:DesignHeight="480" Width="272" Height="110" Template="{DynamicResource MainMenuButtonStyle}">
<Grid x:Name="LayoutRoot"/>
好吧,我試過你的解決方案,但它沒有完全工作。現在,該應用聲稱「ControlTemplate」的TargetType'MainMenuButton'與用作模板的Typ'UserControl'不匹配(來自德語的翻譯錯誤消息,不知道確切的英文消息) 將我的MainMenuButton.xaml編輯爲第一帖子。 – TorbenJ
你試圖做的方法似乎並不理想。 我明白這個問題,有辦法解決它。但是相信你不能爲在自己的控件(xaml)中擴展usercontrol的控件定義模板。 當您在其他控件中使用控件(MainMenuButton)時,可以使用該模板。 有一種替代非傳統。我會編輯我的答案 –
好的,謝謝你的編輯會嘗試。我剛用Expression Blend創建了這個控件,Blend創建了這個模板,所以我認爲它可能是最好的解決方案。 – TorbenJ