사용자 지정 종속성 속성 바인딩에 문제가 있습니다. 우리는이 : 사용자 정의 사용자 한 종속성 속성과 컨트롤과 자기 바인딩 :사용자 지정 종속성 바인딩 바인딩
<UserControl x:Class="WpfApplication1.SomeUserControl"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
mc:Ignorable="d"
d:DesignHeight="300" d:DesignWidth="300" DataContext="{Binding RelativeSource={RelativeSource Mode=Self}}">
<Grid>
<Label>
<Label.Template>
<ControlTemplate>
<Label Content="{Binding MyTest}"/>
</ControlTemplate>
</Label.Template>
</Label>
</Grid>
... 및 제어 코드 : 나는이 컨트롤을 사용하려고
public partial class SomeUserControl : UserControl
{
public SomeUserControl()
{
InitializeComponent();
}
public static readonly DependencyProperty MyTestProperty = DependencyProperty.Register("MyTest", typeof(int), typeof(SomeUserControl));
public int MyTest
{
get { return (int)GetValue(MyTestProperty); }
set { SetValue(MyTestProperty, value); }
}
}
간단한 모델 클래스의 간단한 속성에 바인딩 :
<UserControl x:Class="WpfApplication1.AnotherUserControl"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:wpfApplication1="clr-namespace:WpfApplication1"
mc:Ignorable="d"
d:DesignHeight="300" d:DesignWidth="300" DataContext="{Binding RelativeSource={RelativeSource Mode=Self}}">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition Width="Auto"/>
</Grid.ColumnDefinitions>
<wpfApplication1:SomeUserControl MyTest="{Binding Path=Model.MyNum}" Grid.Column="0"/>
<Label Content="{Binding Path=Model.MyNum}" Grid.Column="1"/>
</Grid>
public class MyModel:INotifyPropertyChanged
{
private int _myNum;
public int MyNum
{
get { return _myNum; }
set { _myNum = value; OnPropertyChanged("MyNum");}
}
public event PropertyChangedEventHandler PropertyChanged;
[NotifyPropertyChangedInvocator]
protected virtual void OnPropertyChanged(string propertyName)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName));
}
}
그러나 결합이 작동하지 않습니다 : 코드
public partial class AnotherUserControl : UserControl
{
public MyModel Model { get; set; }
public AnotherUserControl()
{
Model = new MyModel();
Model.MyNum = 1231;
InitializeComponent();
}
}
... 그리고 모델
23,414,.... 컴파일시 스택에 오류가 없습니다. 이제 statndart wpf 레이블 컨트롤 (동일한 모델 사용)을 사용하여 바인딩하고 내 사용자 지정 컨트롤 및 사용자 지정 속성을 사용하지 마십시오. 이 문제의 원인을 이해하고 해결하도록 도와주세요.
아니요. 작동하지 않습니다. 컨트롤 템플릿에서 바인딩이 정확합니다. 왜냐하면 내가 바인딩을하지 않고 "MyTest"에 값을 할당하면 컨트롤이 제대로 작동하기 때문입니다. 다른 장소에서 외부 바인딩을 작업하지 않습니다. 하지만 난 ControlTemplate 수준에서 괜찮아요. – kirilljk
내 나쁜 .. 당신이 명시 적으로 자식 usercontrol의 datacontext를 설정하는 것을 보지 못했습니다 .. 업데이트 된 대답 – Nitin
작동합니다 작동합니다. 감사합니다) 그러나 RelativeSource 선언을 피할 수 있습니까? 이 Scenerio에서 – kirilljk