사용자 컨트롤의 데이터 컨텍스트
다음을 만드는 중입니다.UserControl
다음과 같은 것을 사용하고 싶습니다.
<controls:ColorWithText Color="Red" Text="Red color" />
지금까지 다음과 같은 유사한 제어를 구현했습니다.
<UserControl x:Class="Namespace.ColorWithText" Name="ThisControl">
<StackPanel Orientation="Horizontal" >
<Border Width="15" Height="15" Background="{Binding Color, ElementName=ThisControl}" />
<TextBlock Text="{Binding Text, ElementName=ThisControl}" />
</StackPanel>
</UserControl>
어디에Color
그리고.Text
코드에 정의된 컨트롤의 종속성 속성입니다.작동하지만 지정ElementName
모든 시간이 불필요해 보입니다.
사용할 수 있는 또 다른 옵션은
<UserControl x:Class=… DataContext="{Binding ElementName=ThisControl}" Name="ThisControl">
지정하지 않음ElementName
s, 하지만 그것도 제게는 깨끗한 해결책으로 보이지 않습니다.
두 가지 질문이 있습니다.
- 그렇지 않은 이유
<UserControl DataContext="{RelativeSource Self}">
일? - 이런 일을 하는 가장 좋은 방법은 무엇입니까?
첫 번째는 다음과 같습니다.
<UserControl DataContext="{Binding RelativeSource={RelativeSource Self}}">
그리고 두 번째 질문은, 제 생각에.ElementName
또는AncestorBinding
에 바인딩하는 가장 좋은 방법UserControl
의 속성.
사용할 수 없는 이유<UserControl DataContext="{RelativeSource Self}">
?
이것이 당신이 컨트롤을 사용하는 것입니다.
<Grid DataContext="{StaticResource ViewModel}">
<!-- Here we'd expect this control to be bound to -->
<!-- ColorToUse on our ViewModel resource -->
<controls:ColorWithText Color="{Binding ColorToUse}" />
</Grid>
이제 컨트롤에서 데이터 컨텍스트를 하드 코딩했기 때문에 View Model이 아닌 ColorWithText 개체에서 ColorToUse 속성을 검색하려고 시도합니다. 이는 분명히 실패할 것입니다.
따라서 사용자 컨트롤에서 데이터 컨텍스트를 설정할 수 없습니다.그것을 이해하게 해준 브란두르에게 감사드립니다.
이런 일을 하는 가장 좋은 방법은 무엇입니까?
대신 컨트롤의 첫 번째 하위 UI 요소에서 DataContext를 설정해야 합니다.
당신이 원하는 경우.
<StackPanel
DataContext="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type UserControl}}}"
Orientation="Horizontal" >
이제 컨트롤을 참조하는 DataContext가 있으므로 상대 바인딩을 사용하여 해당 컨트롤의 모든 속성에 액세스할 수 있습니다.
이에 대한 답변이 있었다는 것을 알지만, 어떤 설명도 이해하지 못합니다.DataContext
그리고 어떻게 작동하는지.이 링크는 거기에 아주 잘 맞습니다.
WPF, Silverlight 및 WP7의 데이터 바인딩에 대해 알고 싶었던 모든 것(파트 2)
당신의 질문에 대한 답변 #1.
그렇지 않은 이유<UserControl DataContext="{RelativeSource Self}">
일?
위 링크의 요약입니다. DataContext
Self at으로 설정하면 안 됩니다.UserControl
요소 수준입니다.이것은 그것이 상속을 깨뜨리기 때문입니다.DataContext
자체로 설정하고 이 컨트롤을 Windows 또는 다른 컨트롤에 배치하면 Windows가 상속되지 않습니다.DataContext
.
DataContext
XAML의 모든 하위 요소 및 의 모든 XAML에 상속됩니다.UserControl
s. 어딘가에 덮어쓰지 않는 한.설정을 통해UserControl
DataContext
그 자체로, 이것은 그것을 덮어씁니다.DataContext
상속을 중단합니다.대신에, XAML의 한 요소 깊이에 그것을 둥지를 틀어라, 당신의 경우,StackPanel
집어넣어요DataContext
여기에 바인딩하고 에 바인딩합니다.UserControl
이렇게 하면 상속이 보존됩니다.
자세한 내용은 아래 링크를 참조하십시오.
WPF/Silverlight에서 재사용 가능한 사용자 컨트롤을 생성하기 위한 간단한 패턴
당신의 질문에 대한 대답 #2 이런 것을 하는 가장 좋은 방법은 무엇입니까?
아래 코드 예제를 참조하십시오.
<UserControl x:Class="Namespace.ColorWithText" Name="ThisControl">
<StackPanel Orientation="Horizontal" DataContext="{Binding ElementName=ThisControl}">
<Border Width="15" Height="15" Background="{Binding Color" />
<TextBlock Text="{Binding Text}" />
</StackPanel>
</UserControl>
이 작업을 수행하면 다음 작업이 필요하지 않습니다.ElementName
제본할 때마다
은 사야합니다해용다음을 .
{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type UserControl}}, Path=Color}
데이터 바인딩 관련 의심은 항상 이 시트를 참조하십시오.
http://www.nbdtech.com/Blog/archive/2009/02/02/.aspxhttp ://www.nbdtech.com/Blog/archive/2009/02/02/wpf-xaml-data-binding-cheat-sheet.aspx
생성자 자체에서 데이터 컨텍스트를 자체로 설정할 수 있습니다.
public ColorWithText()
{
InitializeComponent();
DataContext = this;
}
이제 당신은 간단히 말할 수 있습니다.
<UserControl x:Class="Namespace.ColorWithText" Name="ThisControl">
<StackPanel Orientation="Horizontal" >
<Border Width="15" Height="15" Background="{Binding Color}" />
<TextBlock Text="{Binding Text}" />
</StackPanel>
</UserControl>
절망적인 영혼들을 위해, 그들은 pdross의 대답을 효과적으로 하려고 노력하지만 할 수 없습니다.
세부 사항이 - 중한세빠져습니다있이항부사.Path=DataContext
하위 코드 세그먼트를 추가하면 다음과 같이 작동하기 시작합니다.
<StackPanel DataContext="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type UserControl}}, Path=DataContext}">
언급URL : https://stackoverflow.com/questions/5077377/usercontrols-datacontext
'programing' 카테고리의 다른 글
Git에서 HEAD^와 HEAD~의 차이점은 무엇입니까? (0) | 2023.05.24 |
---|---|
스토리보드에서 간단한 둥근 단추를 만드는 방법은 무엇입니까? (0) | 2023.05.24 |
두 개의 개체 배열 병합 (0) | 2023.05.24 |
도커 엔진과 도커 컨테이너가 작동하는지 확인하는 방법은 무엇입니까? (0) | 2023.05.24 |
DateTime에서 AM/PM 값을 가져오려면 어떻게 해야 합니까? (0) | 2023.05.24 |