[英]MVVM Too many properties
我正在制作一个WPF项目,并试图坚持MVVM模式。 它有近20个UserControl
,每个都有大约10个控件,我希望能够改变它的属性。 对于每一个,我需要能够更改Visibility
和IsEnabled
(框架元素属性),然后更改内容/文本。 这是每个控件至少3个属性。 在所有UserControl
,这使得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都需要它自己的“实例”,它们不共享相同的值。)上述方法的一个缺点是每个控件必须单独绑定所需的属性。 我必须首先......但仍然。
如果我遗漏了什么或者对某些事情不清楚,请提问。
除了使用上面的类之外,有没有办法将每个控件的2+属性组合成更可重用/更容易实现的东西?
我不确定我到底知道你到底是什么,但你可能想考虑使用一个或几个附加的依赖属性: https : //msdn.microsoft.com/en-us/library/ms749011(v = vs10) )的.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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.