繁体   English   中英

WPF绑定到自定义属性不起作用

[英]WPF Binding to Custom Property Not Working

我有这个控件来显示用户控件列表

<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.ItemsItemsControl.Items的。 知道为什么吗?

您错误地实现了依赖项属性。 您应该使用GetValueSetValue方法,而不是创建自动属性。

public static readonly DependencyProperty ItemProperty = 
    DependencyProperty.Register(
        "Item", typeof(LayerItem), typeof(LayerControl));

public LayerItem Item
{
    get { return (LayerItem)GetValue(ItemProperty); }
    set { SetValue(ItemProperty, value); }
}

PS您不应该访问这样的控件: MainWindow.Instance.LayersList.Items.Remove(Item) 您应该改用MVVM。 我也不认为此属性是必需的。 DataContext可能就足够了。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM