English 中文(简体)
通过窗口名称对后面代码中的属性绑定
原标题:Binding to property in code behind through window name

我想将一个文本框绑在窗口的属性上, 该属性在文件后面的代码中定义 。

当使用“ FindAsentor ” 设置相对源来查找窗口时, 当引用窗口时, 绑定成功 。

为什么它不能用它的名字来称呼窗口, 就像我可以把窗口的“标题”属性绑起来一样?

<强>XAML:

<Window x:Class="WpfApplication123.MainWindow"
        x:Name="MyWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="WPF Binding Example" Height="180" Width="237">
<Grid>
    <TextBox Height="23" HorizontalAlignment="Left" Margin="24,24,0,0" Name="textBox1" VerticalAlignment="Top" Width="136"
             Text="{Binding ElementName=MyWindow, Path=Title}"/>
    <TextBox Height="23" HorizontalAlignment="Left" Margin="24,53,0,0" Name="textBox2" VerticalAlignment="Top" Width="136"
             Text="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Window}}, Path=XYZ}"/>
    <TextBox Height="23" HorizontalAlignment="Left" Margin="24,82,0,0" Name="textBox3" VerticalAlignment="Top" Width="136"
             Text="{Binding ElementName=MyWindow, Path=XYZ}" />
  </Grid>
</Window>

后端 < 坚固 > 代码:

namespace WpfApplication123
{
  public partial class MainWindow : Window
  {
    public MainWindow()
    {
      InitializeComponent();
      XYZ = "XYZ!";
    }

    public string XYZ { get; set; }
  }
}
最佳回答

您可以设置这个。 DataContext = 这个, 然后绑在路径上 。

你需要

XYZ = "XYZ";  

初始化元件前

当文本框初始化 XYZ为空时

问题回答

I never used a normal property, but my guess is you need to implement the INotifyPropertyChanged interface, and raise the property changed event in the setter of XYZ. The imho better approach is to use a dependency property directly.

只要让XYZ成为附属财产,它就应该起作用。





相关问题
Anyone feel like passing it forward?

I m the only developer in my company, and am getting along well as an autodidact, but I know I m missing out on the education one gets from working with and having code reviewed by more senior devs. ...

NSArray s, Primitive types and Boxing Oh My!

I m pretty new to the Objective-C world and I have a long history with .net/C# so naturally I m inclined to use my C# wits. Now here s the question: I feel really inclined to create some type of ...

C# Marshal / Pinvoke CBitmap?

I cannot figure out how to marshal a C++ CBitmap to a C# Bitmap or Image class. My import looks like this: [DllImport(@"test.dll", CharSet = CharSet.Unicode)] public static extern IntPtr ...

How to Use Ghostscript DLL to convert PDF to PDF/A

How to user GhostScript DLL to convert PDF to PDF/A. I know I kind of have to call the exported function of gsdll32.dll whose name is gsapi_init_with_args, but how do i pass the right arguments? BTW, ...

Linqy no matchy

Maybe it s something I m doing wrong. I m just learning Linq because I m bored. And so far so good. I made a little program and it basically just outputs all matches (foreach) into a label control. ...

热门标签