programing

WPF 사용자 컨트롤에서의 데이터 바인딩

linuxpc 2023. 4. 21. 20:18
반응형

WPF 사용자 컨트롤에서의 데이터 바인딩

여러 창에서 공유하는 일련의 컨트롤에 대한 사용자 제어를 만들고 있습니다.컨트롤 중 하나는 "프로토콜 번호"로 다른 프로세스의 흐름을 나타내는 라벨입니다.

이 라벨로 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>

다음은 코드 비하인드입니다.

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));
}

이것은 컨스트럭터에서 Protocol Number를 임의의 값으로 설정하면 사용자 컨트롤에 반영되기 때문에 동작하는 것처럼 보입니다.

그러나 최종 창에서 이 사용자 컨트롤을 사용하면 데이터 바인딩이 끊어집니다.

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>

창의 코드 비하인드:

public partial class Window1 : Window
{
    public Window1()
    {
        Number= 15;
        InitializeComponent();
    }

    public int Number { get; set; }
}

그러면 Protocol Number가 0으로 설정되고 Number로 설정된 값은 무시됩니다.

예시를 읽은 적이 있다

출력 창을 보면 바인딩 예외가 나타납니다.

문제는 다음과 같습니다.사용자 컨트롤 내에서 라벨을 사용자 컨트롤의 DP Protocol Number에 바인드하고DataContext예를 들어 요소 이름을 바인딩에 추가해야 합니다.

<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"
    x:Name="uc"
    >
<Label Height="Auto" Name="numberLabel">Protocol:</Label>
<Label Content="{Binding Path=ProtocolNumber, ElementName=uc}" Name="protocolNumberLabel"/>
(...)
</UserControl>

편집: 몇 가지 사항을 명확히 하기 위해 메인 창에서 바인딩을 변경해도 사용자 제어가 작동합니다.그러나 RelativeSource를 사용하여 MainWindow의 DataContext에 바인드해야 합니다.

    <expControl:MainControls ProtocolNumber="{Binding Path=Number, RelativeSource={RelativeSource AncestorType={x:Type Window}}}" />

유효 내용:

<expControl:MainControls DataContext="{Binding RelativeSource={RelativeSource Self}}"
                         ProtocolNumber="{Binding Path=Number, Mode=TwoWay}"/>

=> 를 설정하지 말아 주세요.DataContextUserControl선언, 사용RelativeSource또는ElementName대신 바인딩을 합니다.

를 지정하지 않으면RelativeSource바인딩을 설정해 보겠습니다.DataContext컨스트럭터:

    public Window1()
    {
        Number= 15;
        DataContext = this;
        InitializeComponent();
    }

언급URL : https://stackoverflow.com/questions/11226843/data-binding-in-wpf-user-controls

반응형