0
我試圖用「IsSelected」屬性擴展wpf按鈕。我創建了一個依賴的對象與attatched屬性看起來像這樣:作爲綁定目標的Attatched屬性不更新值
class FormSelectorExtension : DependencyObject
{
public static DependencyProperty IsSelectedProperty =
DependencyProperty.RegisterAttached("IsSelected", typeof(bool), typeof(FormSelectorExtension),
new PropertyMetadata(new PropertyChangedCallback(SelectionChanged)));
public static bool GetIsSelected(DependencyObject obj)
{
return (bool)obj.GetValue(IsSelectedProperty);
}
public static void SetIsSelected(DependencyObject obj, bool value)
{
obj.SetValue(IsSelectedProperty, value);
}
private static void SelectionChanged(DependencyObject obj, DependencyPropertyChangedEventArgs e)
{
Console.WriteLine(obj.ToString());
}
}
我想attatch到由一個ItemsControl生成的屬性按鈕:現在
<ItemsControl x:Name="frameSelector" ItemsSource="{Binding Path=FrameSelectors}" Grid.Column="2" Grid.RowSpan="2" Width="150" VerticalContentAlignment="Stretch" HorizontalAlignment="Stretch">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<UniformGrid Columns="1"/>
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<ItemsControl.ItemTemplate>
<DataTemplate>
<Button Content="{Binding Path=DisplayName}" Command="{Binding Path=ButtonCommand}" CommandParameter="{Binding Path=CommandParameter}"
Style="{StaticResource ResourceKey=FrameSelectorStyle}" FontSize="28" local:FormSelectorExtension.IsSelected="{Binding Path=Selected}"/>
</DataTemplate>
</ItemsControl.ItemTemplate>
的問題,是我的視圖模型的「Selected」屬性與attatched屬性的綁定。如果我使用靜態值,則可以正確調用attatched屬性的「SelectionChanged」事件處理程序。
只要我把綁定,沒有任何反應。 (初始值設置正確,但改變不承認。)
靜態值
local:FormSelectorExtension.IsSelected="True"
綁定
local:FormSelectorExtension.IsSelected="{Binding Path=Selected}"
的代碼,我更新我的視圖模型:
private void ActivateFrame(FormsFrame selectedFrame)
{
ActiveFrame = selectedFrame;
foreach(var selector in FrameSelectors)
selector.Selected = selector.DisplayName == selectedFrame.DisplayName;
OnPropertyChanged("FrameSelectors");
OnPropertyChanged("ActiveFrame");
}
和我的ViewModel:
public class ButtonData
{
public String DisplayName { get; set; }
public bool Selected { get; set; }
public ICommand ButtonCommand { get; set; }
public object CommandParameter { get; set; }
}
謝謝,解決了這個問題。 – Challex