【问题标题】:Data Binding to Nested Properties?数据绑定到嵌套属性?
【发布时间】:2015-01-01 13:53:55
【问题描述】:

我对 WPF 和 XAML 还是很陌生,现在我已经被数据绑定困了好几天了!我只是想将一些嵌套属性绑定到 TextBox 和 ListView(通过 XAML),但我做错了。 这是我的示例代码:

MainWindow.xaml.cs

namespace CounterTestNestedDataBinding
{
    public partial class MainWindow : Window
    {
        public MyModel MyModel { get; set; }

        public MainWindow()
        {
            InitializeComponent();
            MyModel = new MyModel { MyCounter = new Counter() };
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            MyModel.MyCounter.incrementCounter();
        }
    }
}

MyModel.cs

namespace CounterTestNestedDataBinding
{
    public class MyModel : INotifyPropertyChanged
    {
        public Counter _myCounter;
        public Counter MyCounter
        {
            get { return _myCounter; }
            set
            {
                _myCounter = value;
                NotifyPropertyChanged("MyCounter");
            }
        }

        // some other members and properties ...

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

    }
}

Counter.cs

namespace CounterTestNestedDataBinding
{
    public class Counter : INotifyPropertyChanged
    {
        #region Members
        private int _currentNumber;
        private ObservableCollection<int> _historyList;
        #endregion

        #region Constructor
        public Counter()
        {
            _currentNumber = 0;
            _historyList = new ObservableCollection<int>();
        }
        #endregion

        #region Properties
        public int CurrentNumber
        {
            get { return _currentNumber; }
            set
            {
                _currentNumber = value;
                NotifyPropertyChanged("CurrentNumber");
            }
        }

        public ObservableCollection<int> HistoryList
        {
            get { return _historyList; }
            set
            {
                _historyList = value;
                NotifyPropertyChanged("HistoryList");
            }
        }
        #endregion

        public void incrementCounter()
        {
            HistoryList.Add(CurrentNumber);
            CurrentNumber++;
        }

        public override string ToString()
        {
            return string.Format("CurrentNumber: {0}, HistoryList: {1}", _currentNumber, String.Join(",", _historyList));
        }

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

MainWindow.xaml

<Window x:Class="CounterTestNestedDataBinding.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:counterTestNestedDataBinding="clr-namespace:CounterTestNestedDataBinding"
        Title="MainWindow" Height="350" Width="200" ResizeMode="NoResize" WindowStartupLocation="CenterScreen"
        DataContext="{Binding RelativeSource={RelativeSource Self}}"
        >
    <StackPanel Orientation="Vertical">
        <TextBox x:Name="TextBoxCounterCurrent" Text="{Binding MyModel.MyCounter.CurrentNumber}"/>
        <Button Content="Button" Click="Button_Click"/>
        <ListView x:Name="ListViewCounterHistory" Height="75" ItemsSource="{Binding MyModel.MyCounter.HistoryList}"></ListView>
    </StackPanel>
</Window>

我的问题:

  1. 如何绑定嵌套属性?可能吗?为什么像

    Text="{Binding MyModel.MyCounter.CurrentNumber}"
    

    不工作?

  2. XAML 中的“DataContext”设置是否正确?

【问题讨论】:

标签: c# wpf data-binding


【解决方案1】:

像这样在构造函数中设置数据上下文:

public MainWindow()
{
    InitializeComponent();
    MyModel = new MyModel { MyCounter = new Counter() };
    this.DataContext = MyModel;
}

然后你的数据路径当然会改变,因为你绑定的数据在 MyModel 下。您的绑定应更改如下:

<StackPanel Orientation="Vertical">
    <TextBox x:Name="TextBoxCounterCurrent" Text="{Binding MyCounter.CurrentNumber}"/>
    <Button Content="Button" Click="Button_Click"/>
    <ListView x:Name="ListViewCounterHistory" Height="75" ItemsSource="{Binding MyCounter.HistoryList}"></ListView>
</StackPanel>

编辑:

这就是使用 XAML 的方式。

<Window x:Class="WpfApplication1.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="clr-namespace:WpfApplication1"
    xmlns:system="clr-namespace:System;assembly=mscorlib"
    Title="MainWindow" Height="350" Width="525" >
<Window.Resources>
    <local:MyModel x:Key="myModal" />
</Window.Resources>

<StackPanel Orientation="Vertical" DataContext="{StaticResource myModal}">
    <TextBox x:Name="TextBoxCounterCurrent" Text="{Binding MyCounter.CurrentNumber}"/>
    <Button Content="Button" Click="Button_Click"/>
    <ListView x:Name="ListViewCounterHistory" Height="75" ItemsSource="{Binding MyCounter.HistoryList}"></ListView>
</StackPanel>

代码更改如下:

 public partial class MainWindow : Window
{
    public MyModel MyModel { get; set; }
    public MainWindow()
    {
        InitializeComponent();
        //MyModel = new MyModel { MyCounter = new Counter() };
        //this.DataContext = MyModel;
    }

    private void Button_Click(object sender, RoutedEventArgs e)
    {
        var myModel = this.Resources["myModal"] as MyModel;
        if (myModel != null)
        {
            myModel.MyCounter.incrementCounter();
        }
    }
}

顺便说一下,你应该在 MyModel 构造函数中初始化_myCounter

【讨论】:

  • 谢谢!这工作正常。你能告诉我在 XAML(而不是 C#)中设置数据上下文的样子吗?这可能吗?
  • 我感觉还有一个问题要来了:) 你可以从var myModel = this.Resources["myModal"] as MyModel;这样的代码中访问那个模型
  • 嗯,第一种和第二种方法我都试过了,但都没有奏效(当然,我已经删除了 C# 代码中的数据绑定^^)。 &lt;Window.Resources&gt; &lt;local:MyModel x:Key="MyModel"/&gt; &lt;/Window.Resources&gt; 然后&lt;StackPanel Orientation="Vertical" DataContext="{StaticResource MyModel}"&gt;...与其他主题相同。
  • 第一个问题是关于绑定的,是的,绑定是正确的。嵌套绑定确实有效。第二个问题是 DataContext 设置正确,是的,它在 XAML 中设置正确。 @idursun 只需像我提到的那样声明 MyModel 属性,然后查看结果。这就是代码中的问题。
【解决方案2】:

我认为你的结论并不完全正确,而且你实际上忽略了这里的真正问题。

只需将您的财产创建为

private MyModel myModel;

    public MyModel MyModel
    {
        get { return myModel;}
        set { myModel = value;
            NotifyPropertyChanged("MyModel");
        }
    }

问题是在控件初始化后初始化了 MyModel 属性,但是绑定引擎如何知道它必须刷新视图,因为它仍然是 null,因为你没有' t 告诉引擎拉取边界值。

或者只是在视图之前初始化属性的值也可以工作。一世。 e.

public MainWindow()
    {
        MyModel = new MyModel { MyCounter = new Counter() };    
        InitializeComponent();                   
    }

所以 WPF 确实支持嵌套/点式绑定。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-07-19
    • 1970-01-01
    • 2010-10-15
    • 1970-01-01
    • 1970-01-01
    • 2012-05-02
    • 2013-09-16
    • 2010-11-01
    相关资源
    最近更新 更多