c# - 如何将字段绑定(bind)到用户控件

标签 c# wpf xaml

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

    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
        }
    }

从另一个窗口开始,我尝试为最后一个用户控件设置一个值:

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

加载中的窗口包含:

    public List<Problem> list;

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

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

最佳答案

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

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

您应该在 Window 中实现 INotifyPropertyChanged 以让绑定(bind)知道该值已更新。

我不确定你是否在 Xaml ProblemView 中设置了正确的 DataContext,如果你不确定你可以命名 Window 并在绑定(bind)中使用 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
}

关于c# - 如何将字段绑定(bind)到用户控件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7048443/

相关文章:

.net - 如何让 System.Windows.ShowDialog() 返回 'true' ?

javascript - UWP Webview 从网页获取链接到数组

wpf - 如何为特定数据类型的 ListBoxItems 应用样式 setter ?

c# - WPF 用户控件库中的打包字符串

C#,包含不同类型列表的集合

c# - 在 Mac 上从命令行运行 ASP.NET 5 应用程序时是否使用 launchSettings.json?

c# - 在 C++ 逻辑层上转换 int

C# WPF 将 richtextbox 中粘贴的 BitmapImage 转换为二进制

c# - 间歇性 Linq FirstOrDefault 错误 - 索引超出数组范围

C# 字典,键是字符串,值是计数器。近似算法和线程安全