【问题标题】:How can I bind custom properties from View to ViewModel on code behind?如何在后面的代码中将自定义属性从 View 绑定到 ViewModel?
【发布时间】:2016-01-16 21:09:13
【问题描述】:

我创建了一个 Page MainPage 和一个 UserControl Pager。两者都有自己的 ViewModel。在Pager中,有RowsColumnsSource三个依赖属性。我想将这些属性从Pager 的视图传递给Pager 的视图模型。我在 View 后面的代码上试过这个。但它不起作用...PagerViewModel 中的 set 属性永远不会在调试时被调用。请帮帮我...

这里是详细的机制:

MainPageViewModel

↓通过绑定传递值

MainPage

↓用MainPagerViewModel中的值设置属性

Pager(隐藏代码)

↓绑定属性到PagerViewModel

PagerViewModel

↓通过绑定传递值

Pager(XAML)

这里是源码

[MainPageViewModel.cs]

using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Media;
using Client.Model;

namespace Client.ViewModel
{
    public class MainPageViewModel : ViewModelBase
    {
        ...
        public ObservableCollection<IPagableEntry> PagerTableCategoriesItems { get { return TableCategoryRepository.Instance.TableCategories; } }

        public int PagerTableCategoriesRows { get { return 1; } }

        public int PagerTableCategoriesColumns { get { return 3; } }
        ...
    }
}

[MainPage.xaml]

<Page xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
      xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
      xmlns:view="clr-namespace:Client.View"
      xmlns:viewModel="clr-namespace:Client.ViewModel"
      xmlns:resStr="clr-namespace:Client.CommonResources.String"
      x:Class="Client.View.MainPage"
      Style="{StaticResource common}">
    <Page.DataContext>
        <viewModel:MainPageViewModel />
    </Page.DataContext>
    ...

    <view:Pager x:Name="pagerTableCategories"
                Source="{Binding Path=PagerTableCategoriesItems}"
                Rows="{Binding Path=PagerTableCategoriesRows}"
                Columns="{Binding Path=PagerTableCategoriesColumns}">
    </view:Pager>
    ...
</Page>

[Pager.xaml.cs]

using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Data;
using System.Windows.Input;
using Client.Model;
using Client.ViewModel;

namespace Client.View
{
    public partial class Pager
    {

        public static readonly DependencyProperty SourceProperty = DependencyProperty.Register("Source", typeof(ObservableCollection<IPagableEntry>), typeof(Pager), new PropertyMetadata(null, OnSourceChanged));
        public static readonly DependencyProperty RowsProperty = DependencyProperty.Register("Rows", typeof(int), typeof(Pager), new PropertyMetadata(1, OnRowsChanged));
        public static readonly DependencyProperty ColumnsProperty = DependencyProperty.Register("Columns", typeof(int), typeof(Pager), new PropertyMetadata(1, OnColumnsChanged));
        public static readonly DependencyProperty SelectedEntryProperty = DependencyProperty.Register("SelectedEntry", typeof(object), typeof(Pager), new PropertyMetadata(null, OnSelectedEntryChanged));

        public int Rows
        {
            get { return (int)GetValue(RowsProperty); }
            set { SetValue(RowsProperty, value); }
        }

        public int Columns
        {
            get { return (int)GetValue(ColumnsProperty); }
            set { SetValue(ColumnsProperty, value); }
        }

        public object SelectedEntry
        {
            get { return GetValue(SelectedEntryProperty); }
            set { SetValue(SelectedEntryProperty, value); }

        }

        public ObservableCollection<IPagableEntry> Source
        {
            get { return (ObservableCollection<IPagableEntry>)GetValue(SourceProperty); }
            set { SetValue(SourceProperty, value); }
        }

        public Pager()
        {
            InitializeComponent();

            // I want to bind the three custom properties(Rows, Columns, Source) to PagerViewModel's Rows, Columns, Collection
            Binding bindingRows = new Binding("Rows");
            bindingRows.Mode = BindingMode.TwoWay;
            bindingRows.Source = gridPager.DataContext;
            gridPager.SetBinding(RowsProperty, bindingRows);

            Binding bindingColumns = new Binding("Columns");
            bindingColumns.Mode = BindingMode.TwoWay;
            bindingColumns.Source = gridPager.DataContext;
            gridPager.SetBinding(ColumnsProperty, bindingColumns);

            Binding bindingSource = new Binding("Collection");
            bindingSource.Mode = BindingMode.TwoWay;
            bindingSource.Source = gridPager.DataContext;
            gridPager.SetBinding(SourceProperty, bindingSource);
        }

        private void ListBoxEntriesOnSelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            SelectedEntry = (sender as ListBox).SelectedItem;
        }

        private static void OnSelectedEntryChanged(DependencyObject pager, DependencyPropertyChangedEventArgs e)
        {
            (pager as Pager).SelectedEntry = e.NewValue;
        }

        private static void OnSourceChanged(DependencyObject pager, DependencyPropertyChangedEventArgs e)
        {
            (pager as Pager).Source = (ObservableCollection<IPagableEntry>)e.NewValue;
        }

        private static void OnRowsChanged(DependencyObject pager, DependencyPropertyChangedEventArgs e)
        {
            (pager as Pager).Rows = (int)e.NewValue;
        }

        private static void OnColumnsChanged(DependencyObject pager, DependencyPropertyChangedEventArgs e)
        {
            (pager as Pager).Columns = (int)e.NewValue;
        }

    }
}

[Pager.xaml]

<UserControl xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:view="clr-namespace:Client.View"
             xmlns:viewModel="clr-namespace:Client.ViewModel"
             xmlns:resStr="clr-namespace:Client.CommonResources.String"
             x:Class="Client.View.Pager">
    <Grid x:Name="gridPager">
        <Grid.DataContext>
            <viewModel:PagerViewModel />
        </Grid.DataContext>

        ...

        <ListBox x:Name="listBoxEntries"
                 ItemsSource="{Binding Path=Collection}"
                 BorderThickness="0"
                 Margin="0"
                 Style="{StaticResource common}"
                 HorizontalContentAlignment="Stretch"
                 VerticalContentAlignment="Stretch"
                 ItemTemplate="{StaticResource templateTableCategory}"
                 SelectedItem="{Binding Path=SelectedEntry, Mode=TwoWay}"
                 SelectionChanged="ListBoxEntriesOnSelectionChanged">
            <ListBox.ItemsPanel>
                <ItemsPanelTemplate>
                    <UniformGrid Rows="{Binding Path=Rows}"
                                 Columns="{Binding Path=Columns}"
                                 IsItemsHost="True"/>
                </ItemsPanelTemplate>
            </ListBox.ItemsPanel>
        </ListBox>

        ...

    </Grid>
</UserControl>

[PagerViewModel.cs]

using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Windows.Data;
using System.Windows.Media;
using Client.Model;

namespace Client.ViewModel
{
    public class PagerViewModel : ViewModelBase
    {

        ...

        ListCollectionView _listCollectionView;
        ObservableCollection<IPagableEntry> _collection;
        int _rows;
        int _columns;

        public int Rows
        {
            get { return _rows; }
            set
            {
                _rows = value;
                OnPropertyChanged();
            }
        }

        public int Columns
        {
            get { return _columns; }
            set
            {
                _columns = value;
                OnPropertyChanged();
            }
        }

        public ListCollectionView ListCollectionView
        {
            get { return _listCollectionView; }
            set
            {
                _listCollectionView = value;
                OnPropertyChanged();
            }
        }

        public ObservableCollection<IPagableEntry> Collection
        {
            get
            {
                return _collection;
            }

            set
            {
                _collection = value;
                OnPropertyChanged();
            }
        }

        ...

    }
}

【问题讨论】:

  • 基本上你希望值从 mainviewmodel 传递到 usercontrolviewmodel ?
  • 是的!这就是我最终想要的。

标签: c# wpf mvvm binding


【解决方案1】:

您发布的代码有两个明显的问题:

  1. 您的OnXXXChanged() 处理程序不执行任何操作。他们正在响应他们反过来尝试设置的属性的变化。 IE。他们只是在重复通知他们的属性设置,而不是在某些不同的对象中设置属性值。
  2. 您正试图在不存在的属性上设置绑定。 IE。您的代码隐藏SetBinding() 调用的目标是gridPager 对象,它只是一个Grid。它没有任何要设置的 RowsColumnsSource 属性。

暂时假设我们将使用绑定来完成此操作,您遇到第三个问题:

  1. 您将尝试将两个不同的源属性绑定到同一个目标属性。例如。 Pager.Rows 已经是 MainPage.xaml 中建立的绑定的目标,PagerTableCategoriesRows 作为源。它也不能是来自任何其他对象的绑定的目标(最重要的是,来自自身的循环绑定,如果使用 Pager.RowsProperty 依赖属性,这是唯一有意义的源,因为代码正在尝试做)。

我什至不完全清楚这样做是否明智。似乎Pager 元素可以直接绑定到Pager 属性本身,从而继承原始视图模型的值,而不是维护第二个完全独立但预期相同的视图模型。

但是假设,有一些我完全不明白的很好的理由,你打算在这里使用两个不同的视图模型并希望它们保持同步,在我看来你应该能够让它工作通过更改您的 OnXXXChanged() 处理程序,以便它们直接设置视图模型值。例如:

public partial class Pager
{

    public static readonly DependencyProperty SourceProperty = DependencyProperty.Register("Source", typeof(ObservableCollection<IPagableEntry>), typeof(Pager), new PropertyMetadata(null, OnSourceChanged));
    public static readonly DependencyProperty RowsProperty = DependencyProperty.Register("Rows", typeof(int), typeof(Pager), new PropertyMetadata(1, OnRowsChanged));
    public static readonly DependencyProperty ColumnsProperty = DependencyProperty.Register("Columns", typeof(int), typeof(Pager), new PropertyMetadata(1, OnColumnsChanged));
    public static readonly DependencyProperty SelectedEntryProperty = DependencyProperty.Register("SelectedEntry", typeof(object), typeof(Pager));

    public int Rows
    {
        get { return (int)GetValue(RowsProperty); }
        set { SetValue(RowsProperty, value); }
    }

    public int Columns
    {
        get { return (int)GetValue(ColumnsProperty); }
        set { SetValue(ColumnsProperty, value); }
    }

    public object SelectedEntry
    {
        get { return GetValue(SelectedEntryProperty); }
        set { SetValue(SelectedEntryProperty, value); }

    }

    public ObservableCollection<IPagableEntry> Source
    {
        get { return (ObservableCollection<IPagableEntry>)GetValue(SourceProperty); }
        set { SetValue(SourceProperty, value); }
    }

    public Pager()
    {
        InitializeComponent();
    }

    private void ListBoxEntriesOnSelectionChanged(object sender, SelectionChangedEventArgs e)
    {
        SelectedEntry = (sender as ListBox).SelectedItem;
    }

    private static void OnSourceChanged(DependencyObject pager, DependencyPropertyChangedEventArgs e)
    {
        ((PagerViewModel)(pager as Pager).gridPager.DataContext).Collection =
            (ObservableCollection<IPagableEntry>)e.NewValue;
    }

    private static void OnRowsChanged(DependencyObject pager, DependencyPropertyChangedEventArgs e)
    {
        ((PagerViewModel)(pager as Pager).gridPager.DataContext).Rows =
            (int)e.NewValue;
    }

    private static void OnColumnsChanged(DependencyObject pager, DependencyPropertyChangedEventArgs e)
    {
        ((PagerViewModel)(pager as Pager).gridPager.DataContext).Columns =
            (int)e.NewValue;
    }
}

顺便说一句:我不鼓励您在上面使用as。主要原因是,如果由于某种原因演员表失败,那么毫无帮助的NullReferenceException 将是您的第一个明显症状,而不是InvalidCastException

我建议使用as,仅当预期在某些时候,强制转换会失败。当然,在这种情况下,您也总是检查null 结果并适当地处理它。

如果您希望转换始终成功,请使用转换运算符。

【讨论】:

    【解决方案2】:

    此解决方案假设:

    1. 父窗口/页面对 UC 一无所知。但是UC知道它的父母。
    2. UC 依赖于从其父级向下传播到它的 DataContext。

    这段代码的作用:

    1. UC 使用 MainViewModel 的 MainWinProp1 属性创建 2 路绑定。
    2. 在 UC 中所做的任何更改都在 MainViewModel 中可见,反之亦然。

    它是怎么做到的?

    通过它自己的 DataContext 在 UC 中获取 MainViewModel。由于 UC DataContext 自动从 parentwin dctx 获取其值。但可能会发生这种情况,例如,您的 UC 存在于 MainWin 的某个 Grid 中,而该 Grid 正在使用其他一些视图模型。在这种情况下,您必须使用一些 VisualTree 遍历辅助方法来到达根窗口/页面以获取它的数据上下文。

    https://www.dropbox.com/s/5ryc9ndxdu2m6a4/WpfApplication3.rar?dl=0

    如果您不希望您的 UC 依赖于您的父母,而是使用您的 UC,那么您可以随时从父母轻松访问 UC 并做您想做的事。

    【讨论】:

    • 请不要使用外部网站在您的答案中提供重要细节,更不用说实际代码。 Stack Overflow 问题应该是完全独立的、易于理解的,无需依赖外部网站,尤其是那些已知系统性短暂的网站。如果代码对您的答案很重要,请提供a good, minimal, complete code example,清楚地说明您的答案,就像我们期望的问题一样。
    【解决方案3】:

    您的主要困惑是因为Pager 不是视图,而是UserControl

    它们都可以从 UserControl 类继承,但不同之处在于:在 MVVM 中,视图(或子视图又名 DataTemplate)具有绑定到它(通过 DataContext)或其父级的 ViewModel,但没有“功能”,如“代码隐藏”中的。

    另一边的UserControl 永远不会有属于它的 ViewModel(阅读:逻辑不会拆分为 ViewModel),因为 UserControl 旨在跨多个应用程序重用,视图是特定于 ViewModel 并且只能在您的应用程序中使用。

    UserControl 中,隐藏代码是完全有效的(对于依赖属性,其他应用程序视图模型可以绑定到或在隐藏代码中登录)。 UserControl 将公开用于外部数据绑定的 DP。在View 中,这是绝对不行的,并且违反了 MVVM 模式。

    这是一个非常常见的陷阱,新接触 MVVM 的开发人员会遇到并尝试为控件创建 ViewModel 并发现自己卡在了那里。

    话虽这么说,因为(恕我直言,从您上面的示例中,我没有在您的寻呼机中看到任何特定于应用程序的功能)您的 PagerUserControl 它不需要 PagerViewModel 它是代码应该在Pager的代码后面移动。

    附注 从您的 Pager 的 ViewModel 类中应该很明显,您的尝试是在验证 MVVM,因为它保持对 View 的强引用(不仅对 View 类,而且对 ANY WPF 相关类!!!)。

    using System.Collections;
    using System.Collections.Generic;
    using System.Collections.ObjectModel;
    using System.Linq;
    // MVVM Violation, it's part of WPF 
    using System.Windows.Data;
    // MVVM Violation, it's part of WPF (usually PresentationFramework.dll)
    using System.Windows.Media;
    using Client.Model;
    
    namespace Client.ViewModel
    {
        public class PagerViewModel : ViewModelBase
        {
    
            ...
    
            // MVVM Violation, it's a type from Assembly:  PresentationFramework (in PresentationFramework.dll)
            ListCollectionView _listCollectionView;
            ObservableCollection<IPagableEntry> _collection;
            int _rows;
            int _columns;
    
            public int Rows
            {
                get { return _rows; }
                set
                {
                    _rows = value;
                    OnPropertyChanged();
                }
            }
    
            public int Columns
            {
                get { return _columns; }
                set
                {
                    _columns = value;
                    OnPropertyChanged();
                }
            }
    
            public ListCollectionView ListCollectionView
            {
                get { return _listCollectionView; }
                set
                {
                    _listCollectionView = value;
                    OnPropertyChanged();
                }
            }
    
            public ObservableCollection<IPagableEntry> Collection
            {
                get
                {
                    return _collection;
                }
    
                set
                {
                    _collection = value;
                    OnPropertyChanged();
                }
            }
    
            ...
    
        }
    }
    

    如果您创建单独的程序集,则执行 MVVM 会容易得多。

    1. MyApp.Desktop/MyApp.UniversalApp/MyApp.Web:允许引用 PresentationFramework.dll 和下面的所有其他程序集
    2. MyApp.ViewModels:这个程序集只允许包含 ViewModels。仅参考模型、接口、域。严禁引用 Presentation.dll 和 MyApp.Data.*|MSSQL|Oracle|MySQL|SAP。
    3. MyApp.Core/MyApp.Shared/MyApp.Domain:包含您的业务逻辑。参考模型和基础架构
    4. (可选)MyApp.Models:您的模型,仅此而已。
    5. (可选)MyApp.Infrastructure/MyApp.Abstractions:包含您的服务接口(用于存储库或服务)。不引用或仅引用模型
    6. (可选)MyApp.Data.*|MSSQL|Oracle|MySQL|SAP:您的数据库特定实现以及不属于您的域的所有内容。仅参考基础架构和域

    这非常有用,就像您尝试在模型或视图模型中使用 Presentation.dll 中的类型一样,它会失败,因为没有对程序集的引用,您会立即知道:“哇!停在这里。我做错了什么,它违反了 MVVM!"

    粗体下划线 程序集必须能够在其他平台(Web、桌面、WinPhone、Silverlight)上运行和编译,因此不允许它们有此引用查看特定的程序集。数据层可能因平台而异(即 WinPhone 应用程序可能希望使用 SQLite 而不是 MSSQL,Linux 上的 ASP.NET 网站可能更喜欢 MySQL 而不是 MSSQL 等)

    【讨论】:

      【解决方案4】:

      据我所知,问题是在两个视图模型之间创建同步机制。我完全不同意彼得的理论,但我建议你下一个同步解决方案。为了解决这个问题,我建议您使用模型级别的同步。只需将您需要的细节放入一个轻量模型类中,并将这个小模型注入所需的视图模型中。这是方案:

      问候,

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-02-25
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多