指定从哪个命名空间绑定属性

Cat*_*lMF 2 c# wpf xaml namespaces

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

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

示例 DLL - MyTestDLL.dll

namespace MyTestNamespace
{
    public class Application
    {
        public static string TestValue = "TestVal";
        public Application()
        {}
    }
}
Run Code Online (Sandbox Code Playgroud)

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>
Run Code Online (Sandbox Code Playgroud)

Mik*_*bel 5

在 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仅解析一次并且不会观察引用值的更改。