【发布时间】:2015-05-04 02:37:17
【问题描述】:
我的项目是在 MVVM 中实现的。我有一个 MainWindow,它由一个状态栏和一个 tabview 组成。在 tabview 内部,有一个名为“AnnotationView”的 UserControl。 Annotationview 是两个较小的用户控件的父级,称为 TimePicker。 TimePicker 由两个文本框组成,一个用于小时,一个用于分钟。我想使用这个 UserControl 两次(这也是为什么我将它设为自己的 Control,以便以后重用它)。
TimePicker 的 XAML:
<UserControl x:Class="archidb.Views.TimePicker"
x:Name="TimePickerControl"
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" Height="Auto" Width="Auto"
KeyboardNavigation.TabNavigation="Local">
<Grid DataContext="{Binding ElementName=TimePickerControl}">
<Grid.ColumnDefinitions>
<ColumnDefinition/>
<ColumnDefinition Width="5"/>
<ColumnDefinition/>
</Grid.ColumnDefinitions>
<TextBox Style="{StaticResource TextBoxStyle}"
Text="{Binding Path=HourValue}"
x:Name="tbHours"
KeyboardNavigation.TabIndex="0"/>
<TextBlock Style="{StaticResource TextBlockStyle}"
Margin="0 -3 0 5"
Text=":"
Grid.Column="1"/>
<TextBox Grid.Column="2" Style="{StaticResource TextBoxStyle}"
Text="{Binding Path=MinuteValue}"
x:Name="tbMinutes"
KeyboardNavigation.TabIndex="1"/>
</Grid>
</UserControl>
TimePicker 代码隐藏:
public partial class TimePicker : UserControl
{
public static readonly DependencyProperty HourValueProperty = DependencyProperty.Register("HourValue", typeof(string), typeof(TimePicker), new PropertyMetadata("00"));
public string HourValue
{
get { return (string)GetValue(HourValueProperty); }
set { SetValue(HourValueProperty, value); }
}
public static readonly DependencyProperty MinuteValueProperty = DependencyProperty.Register("MinuteValue", typeof(string), typeof(TimePicker), new PropertyMetadata("00"));
public string MinuteValue
{
get { return (string)GetValue(MinuteValueProperty); }
set { SetValue(MinuteValueProperty, value); }
}
public TimePicker()
{
InitializeComponent();
}
}
在 AnnotationControl 中,我像这样插入 UserControl:
<v:TimePicker x:Name="tpStart"
HourValue="{Binding Path=StartHours}"
MinuteValue="{Binding Path=StartMinutes}"
KeyboardNavigation.TabIndex="2"/>
<v:TimePicker x:Name="tpEnde"
HourValue="{Binding Path=EndHours}"
MinuteValue="{Binding Path=EndMinutes}"
KeyboardNavigation.TabIndex="3"
Grid.Row="2"/>
AnnotationControl 的 DataContext 设置为其视图模型,我在其中声明了属性。
问题是,绑定不起作用。我在依赖属性(“00”)中设置的默认值没有显示在任何文本框中。此外,如果我在文本框中写了一些东西,AnnotationControl 的视图模型中的属性不会改变它的值。这个问题已经困扰我好几天了,我到底做错了什么?
【问题讨论】:
标签: c# wpf xaml mvvm user-controls