2017-08-03 116 views
1

我有一个非常简单的用户控件:WPF传数据源到用户控件

<UserControl x:Class="PointOfSale.UserControls.HousesGrid" 
     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="300" d:DesignWidth="300"> 

<ItemsControl x:Name="LayoutRoot" ItemsSource ="{Binding PopularHouses}"> 
    <ItemsControl.ItemsPanel> 
     <ItemsPanelTemplate> 
      <UniformGrid Columns="5"/> 
     </ItemsPanelTemplate> 
    </ItemsControl.ItemsPanel> 

    <ItemsControl.ItemTemplate> 
     <DataTemplate> 
      <ToggleButton 
       Content="{Binding FormattedPanelTimeRemaining}" 
       Style="{StaticResource MetroToggleButtonStyle}" 
       Height="45" 
       Width="80" 
       VerticalAlignment="Center"/> 
     </DataTemplate> 
    </ItemsControl.ItemTemplate> 
</ItemsControl> 

正如你可以看到的ItemSource属性绑定到父的视图模型的PopularHouses财产。这很好。但是,我想要做的是将LayoutRoot元素的ItemSource设置为父窗体上控件插入到XAML中的位置上的其他属性。

最终结果应该是该用户控件的多个实例,绑定到父级的datacontext上的几个不同的属性。

有人可以解释如何实现这个?

+1

你知道你在想反了,对不对? 为什么改变你绑定的属性,而不是让你的viewmodel通用? – Mishka

+1

如果您希望'ItemsSource'从外部* binde-able *,您可以将其暴露为用户控件的依赖属性,并简单地将'LayoutRoot.ItemsSource'绑定到它。请参阅[本答案](https://stackoverflow.com/a/5700294/1997232)。 – Sinatr

回答

0

你只需要使用RelativeSource将你的UserControl的DataContext绑定到第一个ContentControl的datacontext。

DataContext="{Binding Path=DataContext, RelativeSource={RelativeSource AncestorType={x:Type ContentControl}}}" 

我做了下面的示例:

的主窗口XAML

<Window x:Class="WpfDataContext.MainWindow" 
     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
     xmlns:local="clr-namespace:WpfDataContext" 
     Title="MainWindow" Height="350" Width="525" 
     DataContext="{Binding RelativeSource={RelativeSource Self}}"> 
    <Grid> 
     <local:UserControl1/> 
    </Grid> 
</Window> 

我们设置它的DataContext到自我只为这样的目的。在代码隐藏我们定义一个简单的属性来展示它是如何工作的:

public partial class MainWindow : Window 
{ 
    public MainWindow() 
    { 
     InitializeComponent(); 
    } 

    public string SomeString { get; set; } = "Hello"; 
} 

然后,用户控件XAML:

<UserControl x:Class="WpfDataContext.UserControl1" 
      xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
      xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
      DataContext="{Binding Path=DataContext, RelativeSource={RelativeSource AncestorType={x:Type ContentControl}}}"> 
    <Grid> 
     <TextBlock Text="{Binding SomeString}"/> 
    </Grid> 
</UserControl> 

注意我们是如何绑定的DataContext属性,因为这是关键。

我用一个TextBlock为了简单,但原则适用于你的情况也