【问题标题】:Accessing codebehind object in XAML在 XAML 中访问代码隐藏对象
【发布时间】: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 实现,对吧?

提前感谢您的回答。

【问题讨论】:

    标签: wpf xaml


    【解决方案1】:

    尝试将 StackPanel 的 DataContext 设置为 FeedData 对象:

    <StackPanel DataContext="{Binding FeedData}">
    

    ...

    这将强制 StackPanel 查看 DependencyProperty,其中的所有元素都将被引用为 FeedData 的属性。

    只要您将 DataContext 定义为您绑定到其属性的可视元素上方逻辑树中的某个位置的“FeedData”,它就会起作用。

    【讨论】:

      猜你喜欢
      • 2012-07-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多