[英]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.