C#WPF& MVVM |更新具有绑定到对象的属性的数据 [英] C# WPF & MVVM | update data of a property with a binding to the object

查看:105
本文介绍了C#WPF& MVVM |更新具有绑定到对象的属性的数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好,



这实际上是我的第一个问题。我倾向于找到浏览网络的所有答案,但还没有找到问题的答案...



*我已经创建了这个代码,特别是问题,请看下面!*



我一直想弄清楚是否有办法做以下事情:

1)我有一个带IPropertyChanged的视图模型库

2)我有一个模型,例如一个学生模型,有2个属性 - ID和名称。

3)我有一个简单的MainWindow视图,在MainWindowViewModel上设置了datacontext。

4)该视图显示了一个数据网格,该数据网格来自MainWindowViewModel的Students,这是学生的OC - ObservableCollection< student>(随机数据I)插入)。

5)我已经将datagrid配置为具有SelectedItem = {Binding SelectedStudent}

6)我已经为SelectedStudent.ID和SelectedStudent设置了2个文本框.Name,每当我选择一个学生时,这些值都会很好地显示出来。

7)我也是ee文本框文本在UI中的变化,但不在代码中(!!!)

*我设置了UpdateSourceTrigger = OnPropertyChanged,绑定Mode = TwoWay



每当我想尝试通过改变文本框中显示的当前值来编辑属性值时问题就开始了。

也许我不明白我是什么当我以这种方式绑定时,但我在我的属性的获取/设置 - ID和名称上放置了调试断点,似乎没有任何东西调用Set方法(在SelectedStudent上 - 也许这是我问题的一部分? )。



如果我努力工作并在视图模型下创建Id和Name两个新属性并将它们绑定到文本框,则此方法有效。 ..我可以改变它们的值,并且set会调用我可以在属性本身的断点上看到它 - 只有当我尝试更改我的OBJECT的子属性时才会出现问题...



我是否需要设置stackpanel本地数据文本(例如)到别的东西???



只是为了让你知道,我正在与PRISM合作,但我想尽量简单(如果你知道PRISM的答案,我很想知道!)。





非常感谢所有想要帮助的人!



-----------------

代码(一切都在这里!):< br $>
-----

ViewModelBase:

Hi guys,

This is actually my first question here. I tend to find all the answers browsing the net, but haven't found the answer to that question yet...

*I've created this code especially for the question, look below please!*

I've been trying to figure out if there is any way to do something as follows:
1) I have a view model base with IPropertyChanged
2) I have a model for example a student model with 2 properties - ID and Name.
3) I have a simple MainWindow view, which is set on MainWindowViewModel datacontext.
4) The view shows a datagrid bounded to "Students" from MainWindowViewModel which is an OC of students - ObservableCollection<student>(with random data I inserted).
5) I've configured the datagrid to have SelectedItem = {Binding SelectedStudent}
6) I have set 2 text boxes to the SelectedStudent.ID and SelectedStudent.Name, and the values show up nicely whenever I select a student.
7) I also see the changes in the textbox's text in the UI, but not in code(!!!)
* I've set UpdateSourceTrigger=OnPropertyChanged, and binding Mode=TwoWay

The problem starts whenever I want to try to EDIT the properties values by changing the current value shown in the text boxes.
Maybe I don't understand what I'm doing while I bind this way, but I put a debug breakpoint on the "get/set" of my properties - ID and Name, and nothing seems to invoke the "Set" method(On the SelectedStudent - maybe that's part of my problem?).

This works if i work hard and create 2 new properties like "Id", and "Name" under the view model and bind them to the textboxes instead... I could change their value and the "set" would invoke i could see it on the breakpoint in the properties themselves - the problem starts only when I try to change my OBJECT's child properties...

Do I need to set the stackpanel "local" datacontext(for example) to something else???

Just to let you know, I'm working with PRISM, but I want to make this as simple as possible(if you know the answer in PRISM I would love to know!).


Thanks a lot to everyone who tries to help!

-----------------
CODE(Everything is here!):
-----
ViewModelBase:

public class ViewModelBase : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;

    public void OnPropertyChanged([CallerMemberName]string caller = null)
    {
        var handler = PropertyChanged;
        if (handler != null)
        {
            handler(this, new PropertyChangedEventArgs(caller));
        }
    }
}



----------------

MainWindowViewModel:


----------------
MainWindowViewModel:

public class MainWindowViewModel : ViewModelBase
    {
        private ObservableCollection<Student> _students;
        private Student _selectedStudent = null;

        public Student SelectedStudent
        {
            get { return _selectedStudent; }
            set 
            {
                _selectedStudent = value;
                OnPropertyChanged();
            }
        }

        public ObservableCollection<Student> Students
        {
            get { return _students; }
            set
            {
                _students = value;
                OnPropertyChanged();
            }
        }

        public MainWindowViewModel()
        {
            Students = new ObservableCollection<Student>();
            Students.Add(new Student { Id = "0", Name = "Jackson" });
            Students.Add(new Student { Id = "1", Name = "Jenny" });
        }
    }



-----------------

学生:


-----------------
Student:

public class Student : ViewModelBase
{
    private string _id;
    private string _name;

    public string Id
    {
        get { return _id; }
        set { _id = value; OnPropertyChanged(); }
    }

    public string Name
    {
        get { return _name; }
        set { _name = value; OnPropertyChanged(); }
    }

}



-------------------

MainWindow.xaml:


-------------------
MainWindow.xaml:

<Window.DataContext>
    <local:MainWindowViewModel/>
</Window.DataContext>
<Grid>
    <Grid.RowDefinitions>
        <RowDefinition Height="Auto"/>
        <RowDefinition Height="*"/>
    </Grid.RowDefinitions>

    <StackPanel Grid.Row="0">
        <TextBlock Text="Name: "/>
        <TextBox Text="{Binding SelectedStudent.Name, UpdateSourceTrigger=PropertyChanged, Mode=TwoWay}"/>
        <TextBlock Text="Id: "/>
        <TextBox Text="{Binding SelectedStudent.Id, UpdateSourceTrigger=PropertyChanged, Mode=TwoWay}"/>
    </StackPanel>

    <DataGrid Grid.Row="1" x:Name="dgStudents" ItemsSource="{Binding Students, UpdateSourceTrigger=PropertyChanged, Mode=TwoWay}" SelectedItem="{Binding SelectedStudent, UpdateSourceTrigger=PropertyChanged, Mode=TwoWay}" AutoGenerateColumns="True"/>
</Grid>





我的尝试:



我可能做的一切,我在网上看到的很多东西......尝试过去绑定指南,但他们展示的大部分都是我认识的东西..我还没找到这个特定的编辑我正在尝试做的案例 - 非常令人惊讶......



What I have tried:

Everything I possibly could, many things I saw on the net... Tried going over binding guides but all they showed are mostly things I know.. I haven't found this specific editing case that I'm trying to do - pretty surprising...

推荐答案

嗯,他们确实按预期工作。



如果您在SelectedTextBox中写了一些内容并且文本未更新,则在完成后点击Tab,它会更新集合中的值。但对我来说,它可以按照你的意愿工作,而不需要对代码进行任何更改。如果你确实遇到问题,可以尝试一下:



你可以强制在TextChanged上更新绑定,i.a。 :

Well, they do work as expected.

If you write something in the SelectedTextBox and the text isn't updated, hitting Tab when you are completed, it does update the values in your collection. But for me it works as you want it to, without any changes to the code. If you do have problems you might try this out:

You can force the bindings to updated on TextChanged, i.a. :
<StackPanel Grid.Row="0">
    <TextBlock Text="Name: "/>
    <TextBox  x:Name="txtSelectedName" TextChanged="txtSelectedName_TextChanged" Text="{Binding SelectedStudent.Name, UpdateSourceTrigger=PropertyChanged, Mode=TwoWay}"/>



使用后面的代码:


With the code behind:

private void txtSelectedName_TextChanged(object sender, TextChangedEventArgs e)
{
    BindingOperations.GetBindingExpression(txtSelectedName, TextBox.TextProperty).UpdateSource();
}



这应该可以解决你的问题。


This should take care of your problem.


我尝试了这个没有来电者姓名并实际通过了字符串,它对我有用,如果你不想使用后面的代码,另一个解决方法,因为我很少想做这样的事情是使用System.Windows.Interactivity类将它绑定到命令并实现一个Event触发器;但是,我会寻找遗漏的东西。我使用了一个名为student且具有id和name的模型,并且能够绑定到它。我能想到的另一件事是你真的实例化了学生吗?在你的构造函数中
I tried this without the caller name and actually passed the string and it worked for me, another work around if you do not want to use the code behind because I rarely like to do such things is to bind it to a command using the System.Windows.Interactivity class and implementing a Event trigger; however, I will look for something that is being left out. I used an model named student with id and name and was able to bind to it. The only other thing that I can think of is did you actually instantiate Student? In your constructor
SelectedStudent = new Student();



否则这个适合我。

?
Otherwise this works for me.


这篇关于C#WPF&amp; MVVM |更新具有绑定到对象的属性的数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆