简体   繁体   English

从代码隐藏将XAML属性绑定到任意对象

[英]Bind XAML property to arbitrary object from codebehind

I feel like this should be easy, but I've spent the last several hours trying solutions for this and nothing seems to work. 我觉得这应该很容易,但是我花了最后几个小时尝试解决此问题,但似乎没有任何效果。

I have an object in XAML code, and I want to bind one of its properties to an object that was created in the c# codebehind. 我在XAML代码中有一个对象,并且想要将其属性之一绑定到在c#代码背后创建的对象。 This is my strategy so far: 到目前为止,这是我的策略:

<setpwindows:ScalingWindow
    ...
>
    <setpwindows:ScalingWindow.Resources>
        <localwpf:ObjectProvider x:Key="locationProvider"/>
    </setpwindows:ScalingWindow.Resources>
    ...
        ...
            <DataGridTextColumn
                Header="Code Out"
                Binding="{Binding Source={StaticResource locationProvider}, Path=Obj.Name}"
            />
        ...
    ...
</setpwindows:ScalingWindow>

with ObjectProvider as follows: 使用ObjectProvider如下:

class ObjectProvider : DependencyObject
{
    private object _obj;
    public object Obj
    {
        get { System.Diagnostics.Debug.WriteLine("Got object as " + _obj); return _obj; }
        set { _obj = value; System.Diagnostics.Debug.WriteLine("Set object to " + _obj); }
    }

    public static readonly DependencyProperty ObjProperty = DependencyProperty.Register("Obj", typeof(object), typeof(ObjectProvider));

    public ObjectProvider() {}
}

After the window is initialized, I set Obj like this: 窗口初始化后,我将Obj设置如下:

WPFObjects.ObjectProvider locProv = this.FindResource("locationProvider") as WPFObjects.ObjectProvider;
locProv.Obj = _tempLocation;

This finally gives me no binding errors in the output window, but it doesn't actually bind anything. 最终,这在输出窗口中没有出现绑定错误,但实际上并没有绑定任何内容。 What is the standard way of doing this? 这样做的标准方法是什么?

This is all kinds of wrong, here just a few pointers: 这是各种各样的错误,这里只是几个指针:

  • dependency properties are targets of bindings, not sources. 依赖项属性是绑定的目标,而不是源。
  • do you set Obj anywhere? 你在任何地方设置Obj吗? Does that what you set have a name property? 您设置的内容是否具有name属性?

Then, learn about FrameworkElement.DataContext and the notification interfaces you can implement to notify dependency properties about changes in your data sources. 然后,了解FrameworkElement.DataContext和可实现的通知接口,以通知依赖项属性有关数据源中的更改。 see in other people's code hiw eg ViewModels look like and how they are bound to the UI. 请参见其他人的代码,例如ViewModel的外观以及它们如何绑定到UI。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM