簡體   English   中英

綁定到Usercontrol Datacontext而不是SelectedItems datacontext

[英]Binding to Usercontrol Datacontext instead of SelectedItems datacontext

我有一個列表框,其中帶有文本框的網格顯示了當前選中項數據列表框。 (下面的代碼)

問題是我希望在此網格內有一個刪除按鈕,但是它使用的命令位於Usercontrols DataContext中。 如何使按鈕接收UserControls Datacontext內部的命令綁定?

以下代碼位於網格中,可視樹的根是UserControl。

        <ListBox Name="list" ItemTemplate="{StaticResource listTemplate}" ItemsSource="{Binding listCollection, UpdateSourceTrigger=PropertyChanged}">
        </ListBox>

        <Grid DataContext="{Binding ElementName=list, Path=SelectedItem}" Grid.Row="1">
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto"></RowDefinition>
            <RowDefinition Height="Auto"></RowDefinition>
        </Grid.RowDefinitions>
        <TextBlock Margin="7">Name:</TextBlock>
        <TextBox Margin="5" Grid.Column="1" Text="{Binding Path=Name}"></TextBox>
        <Button Grid.Row="1" Command="{Binding DeleteSelectedItemCommand}">Delete Selected Item</Button>
        </Grid>

您的意思是要在您的UserControls DataContext IE虛擬機上觸發按鈕的命令? 然后,您需要此綁定;

<Button Grid.Row="1" Command="{Binding Path=DeleteSelectedItemCommand, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type YourControl}}}">Delete Selected Item</Button>

基本上,這只是遍歷您的xaml樹並從名為YourControl的控件中獲取數據上下文。 您可以在此處設置UserControl。 這種綁定的好處是,您可以追溯鏈中任何項目的數據上下文:)

對於有些棘手的綁定,該文檔仍然非常方便:)

干杯,

了Stian

您需要更改DataContext,為UserControl提供相同的名稱,然后

Command="{Binding ElementName=Name, Path=DeleteSelectedItemCommand}"

訣竅是使用Stians參考連接DataContext。

<Button 
DataContext="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType {x:Type UserControl}}, Path=DataContext}" 
Command="{Binding Path=DeleteSelectedItemCommand}">
</Button>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM