在 XAML 中访问代码隐藏对象 [英] Accessing codebehind object in XAML

查看:28
本文介绍了在 XAML 中访问代码隐藏对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

另一篇博文介绍了如何访问隐藏代码XAML 中的变量.

Another post describes how to access a codebehind variable in XAML.

但是,我想从 XAML 访问代码隐藏 对象 中的变量.代码隐藏对象,称为 FeedData,被声明为 FeedEntry 类型的依赖属性.这个类只是一个具有字符串和日期时间属性的容器类.

However, I'd like to access a variable in codebehind object from XAML. The codebehind object, called FeedData, is declared as a dependency property of type FeedEntry. This class is just a container class with string and datetime properties.

Codebehind 的属性定义是这样的:

Codebehind's property definitition is this:

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 中,我正在这样做,但不起作用:

In XAML I'm doing this, which doesn't work:

<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 设置,它将起作用!像这样:

But if I override Window's datacontext setting in codebehind's contructor, it will work! Like this:

xRoot.DataContext = FeedData;

我理解为什么在 codebeh 中设置 datacontext 时它会起作用.但是我想找到一种方法来获取在代码隐藏中声明的对象中的变量.因为,一切都应该可以通过 XAML 实现,对吗?

I understand why it works when datacontext is set in codebehing. But I'd like to find out a way to grab variables within an object that is declared in codebehind. Because, everything should be doable from XAML, right?

提前感谢您的回答.

推荐答案

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

Try setting the StackPanel's DataContext to the FeedData object:

<StackPanel DataContext="{Binding FeedData}">

...

这将强制 StackPanel 查看 DependencyProperty,并且其中的所有元素都将作为 FeedData 的属性进行引用.

This will force the StackPanel to look at the DependencyProperty, and all elements in it will be referenced as properties of FeedData.

只要您将 DataContext 定义为FeedData",在您绑定到它的属性的可视元素上方的逻辑树中的某处,它就会起作用.

As long as you define the DataContext as "FeedData" somewhere in the logical tree above the visual elements you are binding to properties of it, it will work.

这篇关于在 XAML 中访问代码隐藏对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆