我是一名有用的助手,可以为您翻译文本。
我有一个具有自定义DependencyProperty的UserControl。当我在DataTemplate内部使用UserControl时,无法设置DependencyProperty的值。如果我直接在窗口中使用UserControl,则DependencyProperty正常工作。对于这篇长帖子,我感到抱歉,我将代码简化到最小限度,仍然显示了我在项目中遇到的问题。谢谢任何帮助,我不知道还能尝试什么。
主窗口XAML:
主窗口代码:
我有一个具有自定义DependencyProperty的UserControl。当我在DataTemplate内部使用UserControl时,无法设置DependencyProperty的值。如果我直接在窗口中使用UserControl,则DependencyProperty正常工作。对于这篇长帖子,我感到抱歉,我将代码简化到最小限度,仍然显示了我在项目中遇到的问题。谢谢任何帮助,我不知道还能尝试什么。
主窗口XAML:
<Window ...>
<Window.Resources>
<DataTemplate DataType="{x:Type local:TextVM}">
<local:TextV MyText="I do not see this"/> <!--Instead I see "Default in Constructor"-->
</DataTemplate>
</Window.Resources>
<Grid>
<Border BorderThickness="5" BorderBrush="Black" Width="200" Height="100" >
<StackPanel>
<ContentControl Content="{Binding Path=TheTextVM}"/>
<local:TextV MyText="I see this"/>
</StackPanel>
</Border>
</Grid>
</Window>
主窗口代码:
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
this.DataContext = this;
TheTextVM = new TextVM();
}
public TextVM TheTextVM { get; set; }
}
用户控件 XAML:
<UserControl ...>
<Grid>
<TextBlock x:Name="textBlock"/>
</Grid>
</UserControl>
用户控件代码:
public partial class TextV : UserControl
{
public TextV()
{
InitializeComponent();
MyText = "Default In Constructor";
}
public static readonly DependencyProperty MyTextProperty =
DependencyProperty.Register("MyText", typeof(string), typeof(TextV),
new PropertyMetadata("", new PropertyChangedCallback(HandleMyTextValueChanged)));
public string MyText
{
get { return (string)GetValue(MyTextProperty); }
set { SetValue(MyTextProperty, value); }
}
private static void HandleMyTextValueChanged(DependencyObject d, DependencyPropertyChangedEventArgs args)
{
TextV tv = d as TextV;
if(tv != null) tv.textBlock.Text = args.NewValue.ToString();
}
}