【发布时间】:2009-08-07 21:16:25
【问题描述】:
Another post 描述了如何访问 XAML 中的代码隐藏变量。
但是,我想从 XAML 访问代码隐藏 object 中的变量。名为 FeedData 的代码隐藏对象被声明为 FeedEntry 类型的依赖属性。此类只是具有字符串和日期时间属性的容器类。
Codebehind 的属性定义是这样的:
public FeedEntry FeedData
{
get { return (FeedEntry)GetValue(FeedDataProperty); }
set { SetValue(FeedDataProperty, value); }
}
public static readonly DependencyProperty FeedDataProperty =
DependencyProperty.Register("FeedData", typeof(FeedReaderDll.FeedEntry), typeof(FeedItemUserControl),
new FrameworkPropertyMetadata(new FeedEntry(){ Title="Hi!", Published=DateTime.Now }));
在 XAML 中我正在这样做,但它不起作用:
<UserControl x:Class="FeedPhysics.UserControls.FeedItemUserControl"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Height="40" Width="200"
Background="Blue"
DataContext="{Binding RelativeSource={RelativeSource Self}}"
x:Name="xRoot">
<StackPanel>
<TextBlock Text="{Binding Title}" Foreground="White"/>
<TextBlock Text="{Binding Published}" Foreground="White"/>
</StackPanel>
</UserControl>
但是,如果我在代码隐藏的构造函数中覆盖 Window 的 datacontext 设置,它将起作用!像这样:
xRoot.DataContext = FeedData;
我明白为什么在代码行为中设置数据上下文时它会起作用。但我想找到一种方法来获取在代码隐藏中声明的对象中的变量。因为,一切都应该可以通过 XAML 实现,对吧?
提前感谢您的回答。
【问题讨论】: