数据绑定-C#/WPF-对象依赖性 [英] Data Binding - C# / WPF - Object Dependencies

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

问题描述

大家好,

我大约是C#和WPF的两个月新手.我正在尝试解决以下需要完成的情况.任何帮助将不胜感激.

该场景是我需要实现的,如下所示:

1)如果我有一个具有一个或多个属性的单个数据模型对象,则需要在属性更改时显示它们-我没有问题,因为我使用 INotifyPropertyChanged

2)如果我有一个综合数据模型,则它由两个或多个单一数据模型对象组成.如果单个数据模型中有3个属性,例如名称,得分,排名,则复合数据模型中也有3个相同属性.但是,复合数据模型中属性的值取决于单个数据模型
中属性值的任何变化
这两个模型都实现INotifyPropertyChanged和IBaseModel(请参见我的源代码中的List< ibasemodel>下方)

例如,如果:

SDM1(单一数据模型):[姓名=人,得分= 50,等级= 5]
SDM2(单一数据模型):[名称=女人,得分= 70,等级= 8]

为此的CDM(复合数据模型)应为以下内容:

CDM:[姓名=男人/女人,得分=(70 + 50)/2,等级=(8-5).

3)在我的数据网格中,我应该看到:

曼50 5
女人70 8
男人/女人60 3

4)现在,如果明天将SDM1(男人)的得分更改为30,我的CDM应该将得分的值重新计算为(70 + 30/2),并将数据网格显示更新为:

男人/女人50 3

5)如果再次将SDM2(女性)等级更改为10,我的CDM应该更改为(10-5)

男人/女人50 5

我遇到的主要问题如下:
一个.如何创建对SMD的任何依赖关系,以便如果其中的任何属性发生更改,它都将触发CMD中针对这些特定属性的重新计算,并更改数据网格中的属性值.

我知道我可以使用观察者模式并将CMD注册为观察者,并将SDM中的属性注册为主题,并让CMD属性遵守主题的特定属性(SDM1和SMD2).

但是,我看到的是,仅将CDM中Score的set方法的值分配给以下内容不足以触发WPF的任何此类更改

Hi All,

I''m about 2 months new to C# and WPF. I am trying to solve the following situation that I need to accomplish. Any help would be appreciated.

The scenario is what I need to achieve as follows:

1) If I have a Single Data Model object that has one or more properties, I need to display the properties as when they change - I have no issue with this as I am binding the properties using INotifyPropertyChanged

2) If I have a Composite Data Model, it is made up of two or more of the Single Data Model objects. If there are 3 properties in the Single Data Model such as Name, Score, Rank, then there are also 3 same properties in the Composite Data Model. However, the property values of those in the Composite Data Model are dependent on any change in value of those in the Single Data Model

Both Models implement INotifyPropertyChanged and IBaseModel (see the List<ibasemodel> below in my source code)

For instance, if:

SDM1 (Single Data Model): [Name=Man, Score=50, Rank=5]
SDM2 (Single Data Model): [Name=Woman, Score=70, Rank=8]

The CDM (Composite Data Model) for this should be the following:

CDM : [Name=Man/Women, Score=(70+50)/2, Rank=(8-5).

3) In my Data Grid, I should see:

Man 50 5
Woman 70 8
Man/Woman 60 3

4) Now, if tomorrow, the Score for SDM1 (Man) should change to 30, my CDM should recalculate the value for Score to (70+30/2) and update the Data Grid display for:

Man/Woman 50 3

5) If again, SDM2 (Woman) the Rank changes to 10, my CDM should change to (10-5)

Man/Woman 50 5

The main problem I have having is the following:
a. How can I create any dependency on the SMD''s such that if any property changes in it, it should trigger a a re-calculation in the CMD for those specific properties and change the property value in the data grid.

I know that I can use the Observer pattern and register the CMD as an Observer and the properties in the SDM''s as Subjects and have the CMD properties observe the specific properties of the subject (SDM1 and SMD2).

However, what I''m seeing is that simply assigning the value of set method in the CDM for Score to the following is not enough to trigger any such change to the WPF

// WPF Data Grid - Binding SPREAD
private double _score;
public double Score
{
    get
    {
        Debug.WriteLine(this.ToString() + ": Score - (GET) - [_score=" + _score+ "]");
        return _score;
    }
    set
    {
        Debug.WriteLine(this.ToString() + ": Score - (SET) - [value=" + value + "]");
        this._score= (sdm1.Score - sdm2.Score)/2;
        OnPropertyChanged("Score");
    }
}




我有一个简单的数据网格,如下所示:




I have a simple Data Grid as follows:

<UserControl x:Class="ValueModelTest.MainWindow"

        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"

        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"

        xmlns:dg="clr-namespace:Microsoft.Windows.Controls;assembly=WPFToolkit"

        Height="350" Width="503">
    <UserControl.Resources>
        <ResourceDictionary>
            <CollectionViewSource x:Key="MyDataSource"/>
        </ResourceDictionary>
    </UserControl.Resources>

    <DockPanel Name="DP" LastChildFill="False">
        <dg:DataGrid x:Name="DG" ItemsSource="{Binding Source={StaticResource MyDataSource}}"

                     HeadersVisibility="Column"

                     CanUserAddRows="True"

                     AutoGenerateColumns="False">
            <dg:DataGrid.Columns>
                <dg:DataGridTextColumn Header="Name"

                                       Binding="{Binding NAME}"

                                       Width="150">
                </dg:DataGridTextColumn>

                <dg:DataGridTextColumn Header="A"

                                       Binding="{Binding Score}"

                                       Width="150">
                </dg:DataGridTextColumn>

                <dg:DataGridTextColumn Header="B"

                                       Binding="{Binding Rank}"

                                       Width="150">
                </dg:DataGridTextColumn>

            </dg:DataGrid.Columns>
        </dg:DataGrid>
    </DockPanel>

</UserControl>



在我的MainView.xaml.cs中,我具有以下内容:



In my MainView.xaml.cs, I have the following:

using System;
using System.Collections.Generic;
using System.Collections;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.ComponentModel;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Threading;

using System.Windows.Markup;
using System.Diagnostics;

namespace ValueModelTest
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : UserControl
    {
        // MyModel and MyCompositeModel
        public MyDataModel s2Model;
        public MyDataModel s5Model;
        public MyCompositeModel scModel;

        // Contains all the Main DataModel - Grid
        private static List<IBaseModel> dataSource;
        // DataModel Structure in the XAML
        private static CollectionViewSource dataViewSource;

        // Main
        public MainWindow()
        {
            InitializeComponent();

            this.DataContext = this;

            // Initialize the Data once the WPF Grid Display is initialized
            InitializeData();
        }

        // Load the data into the Grid
        public void InitializeData()
        {
            try
            {
                Debug.WriteLine(this.ToString() + ":InitializeData");

                // DataList Initialize
                dataSource = new List<IBaseModel>();

                // Create the MyModel(2)
                s2Model = new MyModel();
                s2Model.NAME = "Man";
                s2Model.Score= 50;
                s2Model.Rank= 5;
                dataSource.Add(s2Model);

                // Create another MyModel(5)
                s5Model = new MyModel();
                s5Model.NAME = "Woman";
                s5Model.Score= 70;
                s5Model.Rank= 8;
                dataSource.Add(s5Model);

                // Create the Composite MyCompositeModel (Man/Woman)
                scModel = new MyCompositeModel (1, s2Model, s5Model);
                scModel.NAME = s2Model.NAME + "/" + s5Model.NAME;
                dataSource.Add(scModel);

                // Get a handle on the Data Source in the WPF
                dataViewSource = (CollectionViewSource)FindResource("MyDataSource");

                //Populate the WPF Data
                dataViewSource.Source = dataSource;
            }
            catch (Exception ex)
            {
                Debug.WriteLine(this.ToString() + ": InitializeData Error - " + ex.StackTrace.ToString());
            }

            Debug.WriteLine("ValueModelTest: - Testing");
        }
    }
}

推荐答案

嗨 我可能误解了这个问题.但是,当向UI呈现数据时,应该考虑使用
Hi I may have misunderstood the question. But you should concider using
ObservableCollection<IBaseModel>

而不是

List<IBaseModel>

,因为ObservableCollection还实现了通知属性,用于通知列表中的更改.

希望对您有所帮助:-)

when presenting data to the UI, because the ObservableCollection also implements the notification properties notifying changes in the list.

Hope it helps :-)


这篇关于数据绑定-C#/WPF-对象依赖性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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