Kin*_*sin 3 wpf binding user-controls dependency-properties mvvm
正如标题所说,我想将一个属性从我的ViewModel绑定到相应视图中的嵌套UserControl.我不能按照我需要的方式工作.
嵌套的UserControl只不过是DatePicker一个DropDown小时和一个小时.如何告诉DatePicker我们选择ViewModel传播的日期作为其选定日期?
我几乎尝试了一切,现在我离窗户不远了.如你所见,任何帮助表示赞赏;)
现在到目前为止的代码:DateTimePicker.xaml.cs(CodeBehind)
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); }
}
}
Run Code Online (Sandbox Code Playgroud)
嵌套的UserControl(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>
Run Code Online (Sandbox Code Playgroud)
并且,最后但并非最不重要:具有嵌套UserControl的View(View.xaml)
<CustomControls:DateTimePicker SelectedDateValue="{Binding LocalRegistrationStartDate, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" />
希望问题很清楚,任何人都可以帮助我,或者说明我在这里做错了什么.
使用:
"{Binding SelectedDateValue}"
Run Code Online (Sandbox Code Playgroud)
告诉WPF"嘿,检查我DataContext的财产SelectedDateValue".
你想要的是Property从你的用户控制中获取.
最简单的方法是为您的用户控制一个名称,如:
<UserControl x:Name="myControl"/>
Run Code Online (Sandbox Code Playgroud)
然后将绑定修改为:
"{Binding ElementName=myControl, Path=SelectedDateValue}"
Run Code Online (Sandbox Code Playgroud)