加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – MVVM太多属性

发布时间:2020-12-15 21:04:23 所属栏目:百科 来源:网络整理
导读:我正在制作一个 WPF项目,并试图坚持MVVM模式.它有近20个UserControls,每个都有大约10个控件,我希望能够改变它的属性.对于每一个,我需要能够更改Visibility和IsEnabled(框架元素属性),然后更改内容/文本.这是每个控件至少3个属性.在所有UserControls中,这使得
我正在制作一个 WPF项目,并试图坚持MVVM模式.它有近20个UserControls,每个都有大约10个控件,我希望能够改变它的属性.对于每一个,我需要能够更改Visibility和IsEnabled(框架元素属性),然后更改内容/文本.这是每个控件至少3个属性.在所有UserControls中,这使得600个属性……

我玩弄了一个创建ControlProperties类的想法,并让每个控件绑定到正确的实例的成员变量/属性. (例如)

//Code-behind
public class ControlProperties
{
    private bool m_isEnabled;
    public property IsEnabled
    {
        get { return m_isEnabled; }
        set { m_isEnabled = value; notifyPropertyChanged("IsEnabled"); }
    }

    ControlProperties() { m_isEnabled = false; }
}

public ControlProperties controlOne;


//XAML
<Button IsEnabled={Binding controlOne.IsEnabled}/>

除了使用上面的类之外,有没有办法将每个控件的2个属性组合成更可重用/更容易实现的东西? (每个Control都需要它自己的“实例”,它们不共享相同的值.)上述方法的一个缺点是每个控件必须单独绑定所需的属性.我必须首先……但仍然.

如果我遗漏了什么或者对某些事情不清楚,请提问.

解决方法

Is there a way to combine the 2+ properties of each control into something more reusable/easier to implement,other than using the above class?

我不确定我到底知道你到底是什么,但你可能想考虑使用一个或几个附加的依赖属性:https://msdn.microsoft.com/en-us/library/ms749011(v=vs.110).aspx

这样的属性可以在一个独立的类中定义:

namespace WpfApplication1
{
    public class SharedProperties
    {
        public static readonly DependencyProperty IsEnabledProperty = DependencyProperty.RegisterAttached(
            "IsEnabled",typeof(bool),typeof(SharedProperties),new FrameworkPropertyMetadata(false));

        public static void SetIsEnabled(UIElement element,bool value)
        {
            element.SetValue(IsEnabledProperty,value);
        }
        public static bool GetIsEnabled(UIElement element)
        {
            return (bool)element.GetValue(IsEnabledProperty);
        }
    }
}

……然后在任何UIElement上设置:

<Window x:Class="WpfApplication1.Window1"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:WpfApplication1"
        mc:Ignorable="d"
        Title="Window21" Height="300" Width="300">
    <StackPanel>
        <UserControl local:SharedProperties.IsEnabled="True" />

        <Button x:Name="btn" local:SharedProperties.IsEnabled="{Binding SomeSourceProperty}" />
    ...
//get:
bool isEnabled = SharedProperties.GetIsEnabled(btn);
//set:
SharedProperties.SetIsEnabled(btn,true);

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读