[英]Windows Phone 8, use DependencyProperty for a usercontrol, PropertyChangedCallback and CoerceValueCallback issue
[英]how to propertly use CoerceValueCallback in a custom WPF usercontrol
我已經創建了一個用戶控件,我團隊的其他成員只需將其放在視圖上,然后他們就可以動態創建按鈕的ObservrableCollection並綁定到它(功能區欄,但高度根據我們的需求進行了定制),它可以處理位置,樣式等等效果很好,完全可以滿足我們項目的需要,但是它只能在初始加載時起作用,我做了一些挖掘並意識到這是因為我在FrameWorkMetaData中只有一個PropertyChangedCallback,並且沒有為它設置回調CoerceValueCallback,所以我做了一些挖掘工作並進行了設置,但我不確定確切要怎么做-我想這是一個問題,CoerceValueCallback的方法簽名有一個返回對象,並且我只想在任何時候更新按鈕列出更改。 忽略此返回值是否安全? 也許一些代碼可能有所幫助-
這是我的PropertyChangedCallback-當他們第一次分配按鈕列表時被觸發
public static void ButtonListUpdated(DependencyObject source, DependencyPropertyChangedEventArgs e)
{
int count = 0;
var grid = (source as RibbonBarUserControl).ButtonsGrid;
var buttons = e.NewValue as ObservableCollection<Button>;
if (buttons != null)
{
grid.Children.Clear();
foreach (RibbonButton b in buttons)
{
b.Margin = new Thickness(1);
b.Style = (Style)grid.FindResource("ribbonButtonStyle");
ColumnDefinition c = new ColumnDefinition();
grid.ColumnDefinitions.Add(c);
grid.Children.Add(b);
Grid.SetRow(b, 0);
Grid.SetColumn(b, count);
count = ++count;
}
}
}
不,這里是CoerceValueCallback
public static object OnButtonListModified(DependencyObject sender, Object baseValue)
{
//What to do here? Can I essentially ignore the returned object and basically
//copy what I am doing in ButtonListUpdated?
return baseValue;
}
我在網上看到了一些示例,這些示例要簡單得多-例如,如果生日小於結婚年生日=結婚年,當然這有點不同-我正在創建按鈕並更新控件的UI。
OK-謝謝您的任何建議!
我認為您不需要使用CoerceValueCallback。 相反,您應該掛接到集合的CollectionChanged事件中,並在觸發該事件時更新按鈕。
所以像這樣:
public static void ButtonListUpdated(DependencyObject source, DependencyPropertyChangedEventArgs e)
{
var control = source as RibbonBarUserControl;
var buttons = e.OldValue as ObservableCollection<Button>;
if (buttons != null)
buttons.CollectionChanged -= control.OnCollectionChanged;
buttons = e.NewValue as ObservableCollection<Button>;
if (buttons != null)
buttons.CollectionChanged += control.OnCollectionChanged;
control.UpdateButtons();
}
private void OnCollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
{
this.UpdateButtons();
}
private void UpdateButtons() {
// TODO: Update buttons
}
您還可以使用NotifyCollectionChangedEventArgs
的成員確定集合的更改方式,並對按鈕進行最小的更改。 或者您可以每次都完全重建它們。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.