首页 / C# / c# – MVVM太多属性
c# – MVVM太多属性
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了c# – MVVM太多属性,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2399字,纯文字阅读大概需要4分钟。
内容图文
![c# – MVVM太多属性](/upload/InfoBanner/zyjiaocheng/767/116b171836b446d1aef704988bbb29ee.jpg)
我正在制作一个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);
内容总结
以上是互联网集市为您收集整理的c# – MVVM太多属性全部内容,希望文章能够帮你解决c# – MVVM太多属性所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。