簡體   English   中英

如何從 Page.Resources 中的數據模板中將按鈕綁定到 viewmodel 命令?

[英]How can I bind a button to a viewmodel command from within a data template that's in Page.Resources?

在我使用 Windows 應用程序 SDK 的應用程序中,我試圖在我的視圖模型中獲得一個按鈕點擊事件來觸發一個命令。 當數據模板位於頁面和頁面之間時,我已經讓它工作了,但是當數據模板在 Page.Resources 中時,它就不起作用了。 我必須在 Page.Resources 中放置一些數據模板,因為我需要在 TreeView 中有多個數據模板,並根據項目的類型使用 DataTemplateSelector 到 select 正確的一個。 我已經讓模板選擇工作了,但我無法讓按鈕綁定工作。 看起來 ElementName 綁定找不到頁面名稱。 誰能告訴我我做錯了什么?

   <Page.Resources>
        <DataTemplate x:Key="treeViewSFETemplate" x:DataType="models:SFE">
        <TreeViewItem>
            <StackPanel Orientation="Horizontal">
                <TextBlock Text="{Binding SFEName}"/>
                <Button Content="+">
                    <i:Interaction.Behaviors>
                        <core:EventTriggerBehavior EventName="Tapped">
                            <core:InvokeCommandAction Command="{Binding ElementName=thisPage, Path=ViewModel.DeleteSFECommand}"/>
                        </core:EventTriggerBehavior>
                    </i:Interaction.Behaviors>
                </Button>
                <Button Content="-"/>
            </StackPanel>
        </TreeViewItem>
    </DataTemplate>
</Page.Resources>

此行為的原因是您在 DataTemplate 中包裝了TreeViewItem 這將導致TreeViewItem在 Visual Tree 中包含 sub-ListViewItem,並且您無法使用按鈕中的元素名稱訪問正確的 DataContext。 請從您的代碼中刪除TreeViewItem

喜歡:

 <DataTemplate x:Key="treeViewSFETemplate" x:DataType="models:SFE">
        <StackPanel Orientation="Horizontal">
            <TextBlock Text="{Binding SFEName}"/>
            <Button Content="+">
                <i:Interaction.Behaviors>
                    <core:EventTriggerBehavior EventName="Tapped">
                        <core:InvokeCommandAction Command="{Binding ElementName=thisPage, Path=ViewModel.DeleteSFECommand}"/>
                    </core:EventTriggerBehavior>
                </i:Interaction.Behaviors>
            </Button>
            <Button Content="-"/>
        </StackPanel>
</DataTemplate>

假設視圖 model 綁定到頁面的DataContext屬性:

<Page
 ...
 x:Name="MyPage"
 ...
  <Page.Resources>
  ...
    <DataTemplate x:Key="MyDataTemplate">
    ...
      <Button
      ...
        Command="{Binding ElementName=MyPage, Path=DataContext.MyCommand}"
        ...

可以通過在頁面構造函數中的InitializeComponent()之后添加事件處理程序來驗證對屬性DataContext值的更改:

public MyPage()
{
  InitializeComponent();
  ...
  DataContextChanged += MyPage_DataContextChanged;
  ...
}

void MyPage_DataContextChanged(FrameworkElement sender, DataContextChangedEventArgs args)
{
  if (DataContext is MyViewModel vm)
  {
  }
}

暫無
暫無

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

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