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}}}" 
相关问题