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

时间:2014-02-10 11:59:07

标签: c# wpf xaml

假设我有一些像这样的单例类:

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

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

和另一个这样的课程:

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

如果我使用的是C#语法,我会写一些类似的东西:

b.TheProperty = A.Instance.SomeProperty

不幸的是,我必须在XAML中执行此操作。 我知道我可以为B类创建一个依赖属性,也可以实现某种类型的PropertyChanged方法,经过几个小时的沉闷工作后会有一个可怕的“过度杀伤”解决方案。
我希望我错过了一些东西,并且有一种简单的方法可以在xaml中完成:

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

2 个答案:

答案 0 :(得分:1)

我怀疑。您需要使用对象数据提供程序。

<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>

您还需要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;
        }
    }
}

答案 1 :(得分:0)

尝试使用路径关键字,如下所示:

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

并将整个单个实例设置为绑定实例的PropertyName属性