2017-08-03 83 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爲了簡單,但原則適用於你的情況也