2016-03-27 28 views
0

Ben düğmesi tıklandığında Bağlam menüsünü göstermek istiyorum ben de öyle yaptımBind Düğme ContextMenu

<Button Grid.Row="0" 
     Grid.Column="4" 
     Width="30" 
     Height="30" 
     VerticalAlignment="Center" 
     Margin="1,5,0,5" 
     Click="btn_Click" 
     ContextMenuService.IsEnabled="false"> 
      <Button.ContextMenu> 
       <ContextMenu x:Name="popup" 
        ItemsSource="{Binding FavoriteProductCollectionViewModelIns}" 
        DisplayMemberPath="Name"/> 
      </Button.ContextMenu> 
</Button>/ 

private void btn_Click(object sender, RoutedEventArgs e) 
{ 
    popup.Visibility = Visibility.Visible; 
    popup.IsOpen = true; 
} 

sorun çalışmıyor bağlayıcı ve bağlam boştur, bir fikrin nasıl bağlanma sorunu gidermek için aşağıdaki?

cevap

1

ContextMenu, kendi görsel ağacına sahip olan Popup içine yerleştirilmiştir. Sonuç olarak, ContextMenu görsel ağacın bir parçası değildir ve ContextMenu açılır penceresinin dışındaki herhangi bir şeyi çözemez. Sonuç olarak; aşağıda gösterildiği gibi

açıkça ItermsSource özelliğini ayarlayabilirsiniz Bunu düzeltmek için: here gösterildiği gibi

private void btn_Click(object sender, RoutedEventArgs e) 
{ 
    popup.ItemsSource = FavoriteProductCollectionViewModelIns; 
    popup.Visibility = Visibility.Visible; 
    popup.IsOpen = true; 
} 

Alternatif olarak, Popup en PlacementTarget özelliğini kullanabilirsiniz.

XAML:

<Button 
    x:Name="FavoriteProductButton" 
    Width="30" 
    Height="30" 
    VerticalAlignment="Center" 
    Margin="1,5,0,5" 
    Click="btn_Click" 
    ContextMenuService.IsEnabled="false"> 
    <Button.ContextMenu> 
     <ContextMenu x:Name="popup" 
        ItemsSource="{Binding FavoriteProductCollectionViewModelIns }" 
        DisplayMemberPath="Name" 
        DataContext="{Binding PlacementTarget.DataContext, RelativeSource={RelativeSource Mode=Self}}" /> 
    </Button.ContextMenu> 
</Button> 

Kod Arkası:

using System.Collections.Generic; 
using System.Windows; 

public partial class MainWindow : Window 
{ 
    public MainWindow() 
    { 
     InitializeComponent(); 
     FavoriteProductCollectionViewModelIns = new List<FavoriteProductViewModel> 
     { 
      new FavoriteProductViewModel {Name = "Menu 1"}, 
      new FavoriteProductViewModel {Name = "Menu 2"} 
     }; 
     DataContext = this; 
     popup.PlacementTarget = FavoriteProductButton; 
    } 

    public class FavoriteProductViewModel 
    { 
     public string Name { get; set; } 
    } 

    public List<FavoriteProductViewModel> FavoriteProductCollectionViewModelIns { get; set; } 

    private void btn_Click(object sender, RoutedEventArgs e) 
    { 
     popup.Visibility = Visibility.Visible; 
     popup.IsOpen = true; 
    } 
}