Mik*_*keC 2 c# data-binding wpf user-controls dependency-properties
一直撞到墙上,发现是时候发一个问题了.我有以下用户控件
XAML
<UserControl x:Class="WorkDayManager3.WPF.UserControls.TimeControl"
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="46" d:DesignWidth="133" Background="Transparent"
DataContext="{Binding RelativeSource={RelativeSource self}}">
<Grid Height="44" Width="132" Background="Transparent">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="29" />
</Grid.ColumnDefinitions>
<TextBox Name="label" Text="{Binding Text}" Grid.ColumnSpan="5"></TextBox>
</Grid>
Run Code Online (Sandbox Code Playgroud)
C#
public partial class TimeControl : UserControl
{
public string Text
{
get { return (string)GetValue(TextProperty); }
set { SetValue(TextProperty, value); }
}
// Using a DependencyProperty as the backing store for Text. This enables animation, styling, binding, etc...
public static readonly DependencyProperty TextProperty =
DependencyProperty.Register("Text", typeof(string), typeof(TimeControl), new UIPropertyMetadata("N/A"));
public TimeControl()
{
InitializeComponent();
}
Run Code Online (Sandbox Code Playgroud)
在我使用控件的窗口中,它在网格中使用,其datacontext设置为StaticResource
<Grid Grid.Row="1" HorizontalAlignment="Center" DataContext="{StaticResource shiftViewSource}" Name="grid1" Margin="48,10,38,0">
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<TextBox Grid.Column="0" Grid.Row="1" Height="23" TabIndex="2" HorizontalAlignment="Left" Margin="10,5,0,5" Name="shiftNameTextBox" Text="{Binding Path=ShiftName, Mode=TwoWay, ValidatesOnExceptions=true, NotifyOnValidationError=true}" VerticalAlignment="Center" Width="120" />
<my2:TimeControl Grid.Column="0" Grid.Row="2" Height="23" TabIndex="2" HorizontalAlignment="Left" Margin="10,5,0,5" Name="shiftNameTextBox" Text="{Binding Path=ShiftName, Mode=TwoWay, ValidatesOnExceptions=true, NotifyOnValidationError=true}" VerticalAlignment="Center" Width="120" />
<my2:TimeControl Grid.Column="0" Grid.Row="3" Text="THIS WORKS OK"/>
</Grid>
Run Code Online (Sandbox Code Playgroud)
现在绑定到Path ShiftName的TextBox工作正常并显示文本.当我使用我的控件时,它不会显示预期的文本.但是在第二个例子中,我只是将Text依赖属性设置为"THIS WORKS OK",文本按预期显示.为什么绑定适用于TextBox但不适用于我的控件.我究竟做错了什么?
你已经把它DataContext放在了UserControl自己身上.因此,你的绑定TimeControl的Text属性试图找到一个叫做财产ShiftName上你的TimeControl,不是你的静态资源.如果查看visual studio的输出窗口,您应该会看到一条错误消息.
这是从来没有设置一个好主意,DataContext就UserControl无论如何,因为任何人都可以将其覆盖.你可以这样做:
<UserControl x:Name="root" ...>
<Grid DataContext="{Binding ElementName=root}"
...
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
187 次 |
| 最近记录: |