relativeSource와 ancestorLevel을 사용하여 완전히 혼란 스럽습니다. 상대 소스는 다른 요소에서 소스를 가져 오는 데 사용됩니다. 그러나이를 성공적으로 수행하려면 해당 요소가 어느 수준인지 세어야합니다. (디버그하는 방법?) WPF에서 가장 혼란스러운 부분입니다.
내 예에서는 데이터 소스를 바인딩 한 다음 명령을 원하는 컨텍스트 메뉴가 있습니다. 내 VM에서 명령을 얻으려면 바인딩이 어떻게되어야합니까? 감사합니다
<Page.DataContext>
<PDB:UsersViewModel x:Name="vm"/>
</Page.DataContext>
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="*" />
</Grid.RowDefinitions>
<!--Page Header info content-->
<Grid Grid.Row="0">
<TextBlock Text="{Binding SelectedUser.Name}"/>
<TextBlock Text="{Binding ElementName=myGrd, Path=CurrentColumn.DisplayIndex}"/>
</Grid>
<!--Datagrid content-->
<DataGrid x:Name="myGrd"
SelectionMode="Single"
SelectionUnit="Cell"
CurrentItem="{Binding SelectedUser, Mode=TwoWay}"
CurrentColumn="{Binding CurrentColumn, Mode=TwoWay}"
IsReadOnly="True"
Grid.Row="1"
ItemsSource="{Binding FilteredUserList}"
AutoGenerateColumns="True"
CanUserAddRows="False"
>
<DataGrid.Resources>
<ContextMenu x:Key="ContextMenu">
<ContextMenu.Items>
<MenuItem Header="{Binding
RelativeSource={RelativeSource
FindAncestor,
AncestorType={x:Type Page},
AncestorLevel=4}, Path=vm}" />
</ContextMenu.Items>
</ContextMenu>
</DataGrid.Resources>
<DataGrid.CellStyle>
<Style TargetType="DataGridCell">
<Setter Property="ContextMenu" Value="{StaticResource ContextMenu}"/>
</Style>
</DataGrid.CellStyle>
</DataGrid>
</Grid>
메뉴가 시각적 트리의 일부가 아니기 때문에 ContextMenu에서 RelativeSource를 사용할 수 없습니다. 그러나 이것은 Binding Source 및 x : Reference를 사용하여 피할 수 있습니다.
나는 당신의 ViewModel이 이렇게 보인다고 가정합니다
public class UserViewModel
{
public string Header { get; set; }
public ICommand MyCommand { get; }
... more code
}
이제 VM의 Header 및 MyCommand 속성을 바인딩하겠습니다.
<ContextMenu x:Key="ContextMenu">
<ContextMenu.Items>
<MenuItem Header="{Binding Header, Source={x:Reference vm}}"
Command="{Binding MyCommand, Source={x:Reference vm}}"/>
</ContextMenu.Items>
</ContextMenu>
중요한 부분은 ViewModel을 시각적 트리의 어딘가에두고 예제에서했던 것처럼 x : Name을 설정하는 것입니다.
<Page.DataContext>
<PDB:UsersViewModel x:Name="vm"/>
</Page.DataContext>
RelativeSource에 대해 더 알고 싶다면이 질문에 당신과 같은 문제가있는 것 같습니다. 기본적으로 바인딩의 경로는 DataContext.MyViewModelProperty
이어야하고 바인딩의 RelativeSource는 DataContext가 ViewModel로 설정된 요소 여야합니다.
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다