一直在我的頭靠在牆上,並認爲是時候發佈一個問題。我有以下用戶控制問題WPF的數據綁定
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>
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();
}
在我使用它與其的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>
現在,綁定到路徑ShiftName的文本框可正常工作並顯示文本。當我使用我的控件時,它不顯示預期的文本。然而,在第二個例子中,我只是將文本依賴項屬性設置爲「這工作正常」文本顯示如預期。爲什麼綁定工作的文本框,但不是我的控制。我究竟做錯了什麼?
嘗試增加的DataContext =這一點;在你的TimeControl構造函數中。 – eandersson 2011-03-31 17:27:10