WPF绑定到自定义属性不工作
问题描述:
我有这样的控件来显示用户控件WPF绑定到自定义属性不工作
列表<ItemsControl x:Name="LayersList" Margin="10,284,124,0">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<StackPanel Orientation="Vertical"/>
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<ItemsControl.ItemTemplate>
<DataTemplate>
<NaturalGroundingPlayer:LayerControl Item="{Binding}"/>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
的LayerControl控制包含此代码
public partial class LayerControl : UserControl {
public LayerItem Item { get; set; }
public static readonly DependencyProperty ItemProperty =
DependencyProperty.Register(
"Item",
typeof(LayerItem),
typeof(LayerControl),
new PropertyMetadata(null));
public LayerControl() {
InitializeComponent();
}
private void Button_Click(object sender, RoutedEventArgs e) {
// This doesn't work because Item remains null
MainWindow.Instance.LayersList.Items.Remove(Item);
}
}
LayerItem包含此
[PropertyChanged.ImplementPropertyChanged]
public class LayerItem {
public LayerType Type { get; set; }
public string FileName { get; set; }
}
public enum LayerType {
Audio,
Video,
Image
}
问题是:绑定将Item属性设置为null。如果我将绑定更改为{Binding Type}
而不是{Binding}
(并相应地调整属性类型),则该绑定起作用。但我无法找到一种方法来绑定整个对象。我究竟做错了什么?
在旁注中,我试着将ItemsControl.ItemsSource
设置为ObservableCollection<LayerItem>
,但那似乎不起作用。直接添加项目到ItemsControl.Items
正在工作。任何想法,为什么?
答
您错误地实现了依赖项属性。您应该使用GetValue
和SetValue
方法,而不是创建自动属性。
public static readonly DependencyProperty ItemProperty =
DependencyProperty.Register(
"Item", typeof(LayerItem), typeof(LayerControl));
public LayerItem Item
{
get { return (LayerItem)GetValue(ItemProperty); }
set { SetValue(ItemProperty, value); }
}
P.S.您不应该访问像这样的控件:MainWindow.Instance.LayersList.Items.Remove(Item)
。您应该使用MVVM。我也不相信这个属性是必需的。 DataContext
可能就足够了。
修复属性的作品。至于删除该项目,DataContext返回该项目,而不是集合。另外,Parent是空的。我没有找到一种轻松从包含集合中删除的方法,所以我以这种方式解决了这个问题。很想听到更好的解决方案。 – 2014-09-19 13:25:38
@EtienneCharland如果解决方案有效,您应该接受并选择性地向上投票。更好的解决方案是正确使用MVVM。查找有关Caliburn.Micro或MVVM Light等MVVM库的教程。不应该有“Button_Click”开始。 – Athari 2014-09-19 21:18:23