일부 DependencyProperties (여기서는 단 하나의 문자열 속성)와 함께 UserControl을 만들었습니다. UserControl을 인스턴스화 할 때 UserControl의 속성을 설정할 수 있으며 예상 한대로 표시됩니다. Binding을 사용하여 정적 텍스트를 바꿀 때 아무 것도 표시되지 않습니다. 다음과 같이UserControl DependencyProperty에 바인딩
내 UserControl을 보인다 :
<User Control x:Class="TestUserControBinding.MyUserControl"
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="30" d:DesignWidth="100">
<Grid>
<Label Content="{Binding MyText}"/>
</Grid>
</UserControl>
코드가 뒤에 :
namespace TestUserControBinding {
public partial class MyUserControl : UserControl {
public MyUserControl() {
InitializeComponent();
this.DataContext = this;
}
public static readonly DependencyProperty MyTextProperty =
DependencyProperty.Register(
"MyText",
typeof(string),
typeof(MyUserControl));
public string MyText {
get {
return (string)GetValue(MyTextProperty);
}
set {
SetValue(MyTextProperty, value);
}
}// MyText
}
}
내 MainWindow를이 시도, 모든 것이 예상대로입니다 :
<Window x:Class="TestUserControBinding.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:TestUserControBinding"
Title="MainWindow" Height="350" Width="525">
<StackPanel>
<local:MyUserControl MyText="Hello World!"/>
</StackPanel>
</Window>
그러나 작동하지 않음 :
<Window x:Class="TestUserControBinding.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:TestUserControBinding"
Title="MainWindow" Height="350" Width="525">
<StackPanel>
<local:MyUserControl MyText="{Binding Path=Text}"/>
<Label Content="{Binding Path=Text}"/>
</StackPanel>
</Window>
라벨의 동작이 올바른지, 그래서 속성 "텍스트"아무 문제가
내 실수 란 없다? 나는 몇 시간 동안 상고하지만 잊어 버린 것을 찾을 수 없습니다. 당신의 UserControl
에서 다음 바인딩
@Brian ... 코드 "this.DataContext = this;" DataContext를 로컬로 설정해야합니다. 그래야하지 않니? – Nishant
오, 그래, 나는 그것을 놓쳤다. 그러나 만약 당신이'UserControl'을 만들고 있다면, 저는'DataContext'를 수동으로 설정하는 것이 좋지 않다고 생각합니다. DataContext는 컨테이너에서 상속되거나 할당 된 컨텍스트를 나타 내기위한 것입니다. 'RelativeSource' 바인딩은 여러분이 원하는'DataContext' 상속 흐름을 방해하지 않으면 서 원하는 결과 ('DependencyProperty'에 대한 바인딩)를 얻을 수 있도록합니다. 'UserControl' 소비자가 자신의'DataContext'를 설정하면'DataContext'를 무시하려고 시도하면 실패합니다. 정확히 문제가있는 –
입니다.MyUserControl의 DataContext를 자체로 설정하는 대신 MyUserControl의 여는 태그에서'x : Name = "MyName"'을 사용하고 Binding이 다음과 같이 변경됩니다 :''나는 해결책이 필요하다고 생각하지만, 다루기 힘들다. – Buchter