微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

c# – MVVM太多属性

我正在制作一个 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);

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐