繁体   English   中英

如何将字段绑定到用户控件

[英]How can I bind a field to a user control

在我的用户控件中,我有这个属性:

    public static DependencyProperty FooListProperty = DependencyProperty.Register(
        "FooList", typeof(List<Problem>), typeof(ProblemView));

    public List<Problem> FooList
    {
        get
        {
            return (List<Problem>)GetValue(FooListProperty);
        }
        set
        {
            SetValue(FooListProperty, value);
        }
    }

    protected override void OnPropertyChanged(DependencyPropertyChangedEventArgs e)
    {
        base.OnPropertyChanged(e);

        if (e.Property == FooListProperty)
        {
            // Do something
        }
    }

由于另一个 window,我正在尝试为最后一个用户控件设置一个值:

    <local:ProblemView HorizontalAlignment="Center"
                       VerticalAlignment="Center" FooList="{Binding list}" />

并且负载中的 window 包含:

    public List<Problem> list;

    private void Window_Loaded(object sender, RoutedEventArgs e)
    {
        // Some processes and it sets to list field
        list = a;
    }

但是在 XAML 代码中,绑定它不起作用。 不要传递数据。 我错了什么?

您不能绑定到 WPF 中的字段,您必须改为将list更改为属性。

您在UserControl中调用依赖属性FooList并在 Xaml 中调用ResultList但我猜这是问题中的错字。

您应该在Window中实现INotifyPropertyChanged以让 Bindings 知道该值已更新。

我不确定您是否在 Xaml ProblemView中设置了正确的DataContext ,如果您不确定是否可以命名Window并在绑定中使用ElementName

<Window Name="window"
        ...>
    <!--...-->
    <local:ProblemView HorizontalAlignment="Center"
                       VerticalAlignment="Center"
                       ResultList="{Binding ElementName=window,
                                            Path=List}" />
    <!--...-->
</Window>

后面的示例代码

public partial class MainWindow : Window, INotifyPropertyChanged
{
    //...

    private List<Problem> m_list;
    public List<Problem> List
    {
        get { return m_list; }
        set
        {
            m_list = value;
            OnPropertyChanged("List");
        }
    }

    #region INotifyPropertyChanged Members

    public event PropertyChangedEventHandler PropertyChanged;
    private void OnPropertyChanged(string propertyName)
    {
        if (PropertyChanged != null)
        {
            PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }
    }

    #endregion
}

暂无
暂无

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

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