相关疑难解决方法(0)

WPF用户控件中的数据绑定

我正在为几个窗口共享的一系列控件创建一个UserControl.其中一个控件是Label,它根据"协议编号"显示其他一些过程的流程.

我正在尝试使用此Label提供DataBinding,因此Window会在协议编号变量更改时自动反映进程的状态.

这是用户控件XAML:

<UserControl Name="MainOptionsPanel"
    x:Class="ExperienceMainControls.MainControls"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    DataContext="{Binding RelativeSource={RelativeSource Self}}"
    >
<Label Height="Auto" Name="numberLabel">Protocol:</Label>
<Label Content="{Binding Path=ProtocolNumber}" Name="protocolNumberLabel"/>
(...)
</UserControl>
Run Code Online (Sandbox Code Playgroud)

这就是Code-Behind:

public partial class MainControls 
{
    public MainControls()
    {
        InitializeComponent();
    }

    public int ProtocolNumber
    {
        get { return (int)GetValue(ProtocolNumberProperty); }
        set { SetValue(ProtocolNumberProperty, value); }
    }

    public static DependencyProperty ProtocolNumberProperty = 
       DependencyProperty.Register("ProtocolNumber", typeof(int), typeof(MainControls));
}
Run Code Online (Sandbox Code Playgroud)

这似乎是有效的,因为如果在构造函数中我将ProtocolNumber设置为任意值,它将反映在用户控件中.

但是,在最终窗口上使用此用户控件时,数据绑定会中断.

XAML:

<Window x:Class="UserControlTesting.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:expControl="clr-namespace:ExperienceMainControls;assembly=ExperienceMainControls"
    DataContext="{Binding RelativeSource={RelativeSource Self}}"
    >
    <StackPanel>
        <expControl:MainControls ProtocolNumber="{Binding Path=Number, Mode=TwoWay}" />
    </StackPanel>

</Window>
Run Code Online (Sandbox Code Playgroud)

窗口的代码隐藏:

public partial class …
Run Code Online (Sandbox Code Playgroud)

c# data-binding wpf xaml user-controls

32
推荐指数
2
解决办法
8万
查看次数

标签 统计

c# ×1

data-binding ×1

user-controls ×1

wpf ×1

xaml ×1