【问题标题】:Specify what namespace to bind a property from指定从哪个命名空间绑定属性
【发布时间】:2014-11-20 11:12:44
【问题描述】:

我有一个简单的用户控件,我想在其中将标签文本值绑定到 DLL 中的属性。 我的主应用程序允许我通过指定 XAML 来插入我自己的用户控件。

在下面的 XAML 中,我使用的 CheckSubtotal 属性是加载用户控件的应用程序的一部分。此属性填充在控件中没有任何问题。 在下面的 XAML 中,TestValue 属性位于我在 XAML 开头指定的 MyTestDLL.dll 中。此属性未填充在控件中。

示例 DLL - MyTestDLL.dll

namespace MyTestNamespace
{
    public class Application
    {
        public static string TestValue = "TestVal";
        public Application()
        {}
    }
}

XAML 示例

<UserControl 
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"

    xmlns:system="clr-namespace:System;assembly=mscorlib"
    xmlns:systemWindows="clr-namespace:System.Windows;assembly=PresentationFramework" 
    xmlns:local="clr-namespace:MyTestNamespace;assembly=MyTestDLL"
    >

    <Grid>
        <DockPanel>
            <Border DockPanel.Dock="Left" Width="294" Margin="3,0,4,3" CornerRadius="0,0,3,3" Padding="2" BorderBrush="Black" BorderThickness="0" Background="White">
                <DockPanel>
                    <StackPanel DockPanel.Dock="Bottom" HorizontalAlignment="Stretch" Margin="5,0,5,0">
                        <Grid>
                            <Label FontSize="20" Content="SubTotal:" HorizontalAlignment="Left" Margin="10,0,0,0" Width="129.51"/>
                            <Label FontSize="20" HorizontalAlignment="Right" Margin="0,0,21,0" Content="{Binding Path=CheckSubtotal}"/>
                        </Grid>
                        <Grid>
                            <Label FontSize="20" Content="TestValue:" HorizontalAlignment="Left" Margin="10,0,0,0" Width="129.51"/>
                            <Label FontSize="20" HorizontalAlignment="Right" Margin="0,0,21,0" Content="{Binding Path=TestValue}"/>
                        </Grid>
                    </StackPanel>
                </DockPanel>
            </Border>
        </DockPanel>
    </Grid>

</UserControl>

【问题讨论】:

    标签: c# wpf xaml namespaces


    【解决方案1】:

    在 XAML 中引用成员的命名空间限定语法为 namespacePrefix:Type.Member,或者在您的情况下为 local:Application.TestValue。请注意,在 PropertyPath 中使用限定成员名称时,该成员应括在括号中,例如 {Binding Path=(ns1:A.B).(ns2:C.D)}

    但是,由于您正在“绑定”到静态成员,因此您可以简单地使用{x:Static local:Application.TestValue}。 WPF 4.0 和更早的版本不支持绑定到静态成员,所以x:Static 是唯一的方法,但请记住x:Static 只解析一次,不会观察到引用值的变化。

    【讨论】:

    • 我将我的属性更改为非静态的。将我的绑定更改为 {Binding Path=(local:Application.TestVal)}。但是我收到错误。 “解析 XAML 时出错。无法将属性路径中的字符串 '(local:Application.TestVal)}' 转换为 System.Windows.PropertyPath 类型的对象。属性路径无效。
    • 这是确切的错误信息吗?看起来您的绑定路径中可能有一个流浪的}
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多