简体   繁体   English

XAML如何在不绑定的情况下设置简单属性值

[英]XAML How to set simple property value without binding

Suppose I have some singleton class like this: 假设我有一些像这样的单例类:

class A
{
    public static A Instance {
        get { return me; }
    }

    public Object SomeProperty
    {
        get { return something; }
    }
}

and another class like this: 和另一个这样的类:

class B
{
    public Object TheProperty
    {
        get { return tp; } 
        set { tp = value; }
    }
}

If I were using C# syntax, I would write something like: 如果我使用的是C#语法,我会写类似以下内容:

b.TheProperty = A.Instance.SomeProperty

Unfortunately, I have to do this in XAML. 不幸的是,我必须在XAML中执行此操作。 I know I could create a Dependency Property for class B , also implement the PropertyChanged method of some sort, and after several hours of dull work have a monstrous "overkill" solution. 我知道我可以为类B创建一个Dependency Property ,也可以实现某种PropertyChanged方法,并且经过数小时的沉闷工作后才有了一个可怕的“过大杀手”解决方案。
I hope that I am missing something, and there is an easy way to do it in xaml like: 我希望我缺少一些东西,并且有一种简单的方法可以在xaml中完成,例如:

<B TheProperty={??A.Instance.SomeProperty} />

As i suspected. 如我所怀疑。 You need to use an object data provider. 您需要使用对象数据提供程序。

<Window x:Class="DataPRoviderTest.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="clr-namespace:DataPRoviderTest"
    Title="MainWindow" Height="350" Width="525">
<Window.Resources>
    <ObjectDataProvider x:Key="provider" ObjectType="{x:Type local:B}">
        <ObjectDataProvider.ConstructorParameters>
            <x:StaticExtension MemberType="{x:Type local:A}" Member="Instance"/>
        </ObjectDataProvider.ConstructorParameters>
    </ObjectDataProvider>
</Window.Resources>
<Grid>
    <TextBlock Text="{Binding TheProperty, Source={StaticResource provider}}"/>
</Grid>
</Window>

You also need a new constructor for B that takes an instance of A . 您还需要B的新构造函数,该构造函数采用A的实例。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DataPRoviderTest
{
    public class A
    {
        public static A Instance
        {
            get { return new A(); }
        }

        public Object SomeProperty
        {
            get { return "Hi there"; }
        }
    }

    public class B
    {
        public Object TheProperty
        {
            get { return tp; }
            set { tp = value; }
        } Object tp = null;

        public B(A instance)
        {
            TheProperty = instance.SomeProperty;
        }
    }
}

try use the path keyword like this: 尝试使用如下路径关键字:

<TextBlock Text="{Binding Path=PropertyName.SomeProperty}" />

and set the entire single instance to the PropertyName property of the instance which is binding 并将整个单个实例设置为要绑定的实例的PropertyName属性

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

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