[英]WPF :: Custom Control's Dependency Properties Aren't Working
我正在為WYSIWYG HTML編輯器制作Ribbon
控件。 功能區具有您期望看到的典型的粗體,斜體,下划線,FontFamily等控件。 在此示例中,我將重點介紹粗體功能。
我希望Ribbon
是可重用的,因此我在后面的控件代碼(標准樣板內容)中添加了依賴項屬性(DP)和關聯的屬性包裝器:
public partial class EditorRibbon: UserControl
{
public static readonly DependencyProperty IsBoldProperty =
DependencyProperty.Register(
"IsBold",
typeof (bool),
typeof (EditorRibbon),
new PropertyMetadata(default(bool)));
public bool IsBold
{
get { return (bool) GetValue(IsBoldProperty); }
set { SetValue(IsBoldProperty, value); }
}
}
...並且在XAML中,我具有RibbonToggleButton
,並將IsChecked
屬性綁定到依賴項屬性:
<UserControl x:Class="My.EditorRibbon">
<r:RibbonToggleButton Command="ToggleBold"
ToolTip="{Binding RelativeSource={RelativeSource Self}, Path=Command.Text}"
SmallImageSource="{StaticResource ToggleBoldIcon}"
IsChecked="{Binding IsBold}" />
</UserControl>
在我的Editor
窗口中,我已經綁定的IsBold
的財產EditorRibbon
對窗口的視圖模型的常規屬性:
<Window x:class="My.MainWindow>
<My.EditorRibbon IsBold="{Binding SelectionIsBold}"/>
</Window>
這是SelectionIsBold
屬性:
public bool SelectionIsBold
{
get { return _selection.IsBold(); }
}
...,並且只要RichTextBox
的選擇發生更改,我都會引發NotifyPropertyChanged()
事件(在MainWindow的ViewModel中):
public class MainWindowViewModel : BaseViewModel
{
public MainWindowViewModel(MainWindow window)
{
rtb.SelectionChanged += rtb_OnSelectionChanged;
}
private void rtb_OnSelectionChanged(object sender, RoutedEventArgs routedEventArgs)
{
NotifyPropertyChanged(()=>SelectionIsBold);
}
}
在我看來,只要選擇更改,就足以更改RibbonToggleButton
的IsChecked
狀態……但實際上並沒有。 盡管更改了選擇,並且按預期方式觸發了NotifyPropertyChanged()
,但從未擊中SelectionIsBold
屬性的斷點( 是的,我取消選擇了VS的“ Step Over Property”設置 )。 在某個地方,刷新值的請求未正確傳播。
在設置器中設置值后,是否需要在IsBold屬性上觸發NotifyPropertyChanged()?
將IsBold綁定更改為以下內容
<UserControl x:Class="My.EditorRibbon" x:Name="EditorRibbonInstance">
<r:RibbonToggleButton Command="ToggleBold"
ToolTip="{Binding RelativeSource={RelativeSource Self}, Path=Command.Text}"
SmallImageSource="{StaticResource ToggleBoldIcon}"
IsChecked="{Binding IsBold, ElementName=EditorRibbonInstance, Mode=TwoWay}" />
</UserControl>
這樣,您可以確保綁定將轉到控件的屬性,而不是控件的datacontext
您必須在ViewModel中觸發notifypropertychanged。 在ViewModel中嘗試以下操作:
protected void FirePropertyChanged(string propertyName)
{
if (this.PropertyChanged != null)
{
this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
->> FirePropertyChanged("SelectionIsBold")
原因是:現在,您的數據上下文是ViewModel,所有綁定到ViewModel的操作都必須由ViewModel的屬性觸發
首先,我之前從未見過將Window注入到ViewModel中...您是否在使用某種類型的DI進行注入?
我認為在viewmodel上使用選擇更改的事件不是一個好主意...從我的角度來看,這不是mvvm ...
您要在某處更新_selection嗎? 可能是您始終檢查相同的選擇嗎?
您沒有正確綁定按鈕的command屬性。
應該反映出這樣的東西:
Command="{Binding ToggleBold}"
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.