WPF-MVVM绑定ViewModel属性嵌套用户控件
正如标题所说,我想要从我的ViewModel属性绑定到相应视图中的嵌套UserControl。 我无法按我需要的方式工作。WPF-MVVM绑定ViewModel属性嵌套用户控件
嵌套UserControl不过是一个DatePicker
和DropDown
几个小时。我怎样才能告诉DatePicker
选择ViewModel传播的日期作为选定的日期?
我尝试了几乎所有的东西,现在我离窗外不远了。 正如你可以看到任何帮助表示赞赏;)
我们到目前为止的代码:DateTimePicker.xaml.cs(代码隐藏)
public partial class DateTimePicker
{
public static DependencyProperty SelectedDateValueProperty = DependencyProperty.Register("SelectedDateValue", typeof (DateTime), typeof (DateTimePicker), new FrameworkPropertyMetadata(default(DateTime), FrameworkPropertyMetadataOptions.BindsTwoWayByDefault, OnPropertyChangedCallback));
private static void OnPropertyChangedCallback(DependencyObject dependencyObject, DependencyPropertyChangedEventArgs args)
{
Debug.WriteLine("Wohoo. I'm here and still debugging...");
}
public DateTimePicker()
{
InitializeComponent();
DataContext = this;
var times = GetTimes();
Times.ItemsSource = times;
Times.SelectedItem = times.First();
}
public DateTime SelectedDateValue
{
get { return (DateTime) GetValue(SelectedDateValueProperty); }
set { SetValue(SelectedDateValueProperty, value); }
}
}
嵌套的用户控件(DateTimePicker.xaml):
<UserControl x:Class="Framework.Controls.DateTimePicker"
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"
mc:Ignorable="d"
d:DesignHeight="30" d:DesignWidth="200"
DataContext="{Binding RelativeSource={RelativeSource Self}}">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="3*" />
<ColumnDefinition Width="2*" />
</Grid.ColumnDefinitions>
<DatePicker HorizontalAlignment="Left" Name="DatePickerCalendar" HorizontalContentAlignment="Stretch" VerticalContentAlignment="Center" SelectedDate="{Binding SelectedDateValue}" />
<ComboBox Grid.Column="1" VerticalAlignment="Center" Name="Times" DisplayMemberPath="Name" />
</Grid>
而且,最后但并非最不重要:视图具有嵌套的用户控件(View.xaml)
<CustomControls:DateTimePicker SelectedDateValue="{Binding LocalRegistrationStartDate, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" />
希望这个问题很明确,任何人都可以帮助我,或者在我这里做错了什么。
使用:
"{Binding SelectedDateValue}"
告诉WPF “嘿检查我DataContext
一个名为SelectedDateValue
财产”。
你想要的是从你的用户控制中获得Property
。
最简单的办法就是给你的用户控制像一个名字:
<UserControl x:Name="myControl"/>
,然后修改你的绑定:
"{Binding ElementName=myControl, Path=SelectedDateValue}"
的常用方法WPF的控制措施是使用模板而不是将控件定义为直接内容,就像你在这里做的那样。通过使用Template
,您可以访问TemplateBinding,使您可以轻松地绑定您的控件属性。请参阅Control Customization MSDN页面。
<ControlTemplate TargetType="{x:Type local:DateTimePicker>
...
<DatePicker SelectedDate="{TemplateBinding SelectedDateValue}" />
...
</ControlTemplate>
感谢您的回复。我给了我的UserControl一个名字,并且像你所描述的那样改变了这个UserControl中的绑定。在运行时它告诉我,'错误:LocalRegistrationStartDate属性找不到'对象'''DateTimePicker''...'这是我的UserControl。那么我是否设置了错误的绑定? – KingKerosin 2012-04-18 15:16:22
好的。似乎现在工作。我不得不删除一些其他论坛中发现的其他论坛,而这些论坛并不是我想让他们做的;-) – KingKerosin 2012-04-18 15:21:09