2012-07-31 62 views
1

我需要將我的ComboBox綁定到UserControl(而不是包含我的ComboBox的ListView的ItemSources)的DataContext的'Rayons'屬性。DataControl上的UserControl的DataContext而不是WPF/MVVM中的ListBox DataBind

我試圖使用RelativeSource,但它不起作用,我在調試窗口中沒有錯誤消息。

簡化代碼:

<UserControl xmlns:my="clr-UI.View" 
      x:Class="UI.View.MontureView" 
      xmlns:i="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity" 
      xmlns:cmd="clr-namespace:GalaSoft.MvvmLight.Command;assembly=GalaSoft.MvvmLight.Extras.WPF4" 
      xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
      xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
      xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
      xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
      mc:Ignorable="d" 
      d:DesignHeight="673" d:DesignWidth="980"> 
     <ListView ItemsSource="{Binding Path=Monture, Mode=TwoWay}" Margin="0,39,0,95" Height="600" HorizontalAlignment="Center"> 
      <ListView.View> 
       <GridView> 
        <GridViewColumn > 
         <GridViewColumn.CellTemplate > 
          <DataTemplate> 
           <ComboBox Height="25" HorizontalAlignment="Center" Width="125" 
              Name="comboBoxRay" Margin="0,2,0,3" 
              ItemsSource="{Binding Path=Rayons, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type UserControl}}}" 
              SelectedValue="{Binding Path=IDRayon, Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}" 
              DisplayMemberPath="SRAY_LIBELLE" 
              SelectedValuePath="SRAY_ID" /> 
          </DataTemplate> 
         </GridViewColumn.CellTemplate> 
        </GridViewColumn> 
       </GridView> 
      </ListView.View> 
     </ListView> 
</UserControl> 

我如何處理這種情況?

我發現documentation,但它並沒有幫助

回答

1

有幾種方法可以解決這個問題。但首先如果你沒有看到綁定錯誤嘗試使用Snoop來查看是否存在綁定錯誤。

然而,如果您使用RelativeSource綁定您的路徑應該alomost是這樣的:Path = DataContext .Rayons。在你的情況下,綁定需要在你的用戶控件上有一個Rayons屬性,但是當然沒有Rayons屬性。

中的RelativeSource像你那樣結合最的作品的時候,但是當你在一個usercontrol一個UserControl有一個用戶控件變得困難;)是這樣的情況下,我使用DataContextMarkerInterface(空接口)。

public interface IDataContextMarkerRayonsSource {} 

那麼這個接口添加到您的特定用戶控件和更改的RelativeSource結合AncestorType

ItemsSource="{Binding Path=DataContext.Rayons, RelativeSource={RelativeSource AncestorType={x:Type local:IDataContextMarkerRayonsSource }}}" 
1

你說:財產的UserControlDataContext。嘗試

ItemsSource="{Binding Path=DataContext.Rayons, 
         RelativeSource={RelativeSource AncestorType={x:Type UserControl}}}" 
相關問題