我试图用"IsSelected“属性扩展wpf按钮。我创建了一个依赖项对象,其属性如下所示:
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());
}
}我想要对属性进行修改的按钮由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“属性绑定到所访问的属性上。如果我使用的是静态值,那么可以正确地调用属性的"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; }
}发布于 2015-06-23 16:01:02
假设FrameSelectors是ButtonData实例的集合,那么您也必须在ButtonData类上实现INotifyPropertyChanged:
public class ButtonData : INotifyPropertyChanged
{
private bool selected;
public bool Selected
{
get { return selected; }
set
{
selected = value;
OnPropertyChanged("Selected");
}
}
...
}请注意,您的FormSelectorExtension类不需要从DependencyObject派生。这只对常规依赖属性是必需的,而对于附加属性则不是必需的。
https://stackoverflow.com/questions/31005408
复制相似问题