绑定到XAML中的Self/'this' [英] Binding to Self/'this' in XAML

查看:65
本文介绍了绑定到XAML中的Self/'this'的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

简单的WPF/XAML问题.在XAML中,如何在给定上下文中引用Self/this对象?在一个非常基本的应用程序中,它具有一个主窗口,一个控件以及该窗口的编码C#属性,我想将该控件的属性绑定到该窗口的手工编码属性.

Simple WPF/XAML question. In XAML, how do I reference the Self/this object in a given context? In a very basic app with a main window, one control, and a coded C# property of the window, I want to bind a property of the control to the hand coded property of the window.

在代码中,这非常简单-在Window的构造函数中,我添加了以下内容:

In code, this is very easy - in the Window's constructor, I added this:

Binding bind = new Binding();
bind.Source = this;
bind.Path = new PropertyPath("ButtonWidth");
button1.SetBinding(WidthProperty, bind);

很显然,我有一个名为ButtonWidth的属性和一个名为button1的控件.我不知道如何在XAML中执行此操作.像下面的示例这样的各种尝试均无效:

Obviously, I have a property called ButtonWidth, and a control called button1. I can't figure out how to do this in XAML. Various attempts like the following example have not worked:

<Button x:Name="button1" Width="{Binding Source=Self Path=ButtonWidth}"/>

<Button x:Name="button1" Width="{Binding RelativeSource={RelativeSource Self} Path=ButtonWidth}"/> 

谢谢

推荐答案

在绑定中首先在RelativeSource和Path之间使用逗号:

First use a comma between the RelativeSource and Path in your Binding:

<Button x:Name="button1" Width="{Binding RelativeSource={RelativeSource Self}, 
                                Path=ButtonWidth}"/> 

第二,RelativeSource绑定到Button.Button没有名为ButtonWidth的属性.我猜您需要绑定到父控件.

Secondly, the RelativeSource binds to the Button. Button has no property called ButtonWidth. I am guessing you need to Bind to your parent control.

因此,请尝试以下RelativeSource绑定:

So try this RelativeSource binding:

<Button x:Name="button1" Width="{Binding RelativeSource=
    {RelativeSource FindAncestor, AncestorType={x:Type YourNamespace:YourParentControl}}, 
    Path=ButtonWidth}"/> 

这篇关于绑定到XAML中的Self/'this'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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