我目前正在嘗試遵循C#4中的MVVM,但遇到了綁定工作的麻煩。C#綁定無法使用屬性<T>
從底部開始,這裏是我的財產類應該照顧性質的改變XAML綁定:
namespace Visualizer.MVVM
{
public class Property<T> : DependencyObject, INotifyPropertyChanged
{
//private T _Value;
public T Value
{
get { return (T) GetValue(ValueProperty); }
set
{
SetValue(ValueProperty, value);
OnPropertyChanged();
}
}
public event PropertyChangedEventHandler PropertyChanged;
protected void OnPropertyChanged()
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs("Value"));
}
}
public Property(T val)
{
Value = val;
}
public static readonly DependencyProperty ValueProperty =
DependencyProperty.Register("Value", typeof(T), typeof(Property<T>));
}
}
我對控制視圖模型看起來像這樣在MainWindow.xaml被實例化的.cs:
public class CheckboxControlVM
{
public Property<bool> IsChecked { get; set; }
public Property<string> Name { get; set; }
public CheckboxControlVM(bool isChecked, string name)
{
IsChecked = new Property<bool>(isChecked);
Name = new Property<string>(name);
}
}
控制沒有代碼隱藏,所以這裏是它的XAML:
<UserControl x:Class="Visualizer.MVVM.Checkbox"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:local="clr-namespace:Visualizer.MVVM"
mc:Ignorable="d"
d:DesignHeight="300" d:DesignWidth="300">
<StackPanel Orientation="Horizontal" x:Name="LayoutRoot">
<CheckBox IsChecked="{Binding Path=IsChecked.Value, Mode=TwoWay}"/>
<TextBlock Text="{Binding Path=Name.Value, Mode=OneWay}"/>
</StackPanel>
</UserControl>
最後,這裏是MainWindow.xaml綁定:
<mvvm:Checkbox DataContext="{Binding Realtime}"/>
我一直停留在這了很多的時間比我要和我相當肯定它只是一個簡單的問題。有任何想法嗎?
並注意:也沒有綁定錯誤。 – HoboSteaux 2013-04-04 05:05:48