WPF将数据源传递到用户控件

3

我有一个非常简单的用户控件:

<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属性绑定到父ViewModel上的PopularHouses属性。这非常好用。然而,我想做的是在插入控件的那一点上将LayoutRoot元素的ItemSource设置成不同的属性。

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

有人能解释一下如何实现吗?


1
你意识到你的思路是反向的,对吧? 为什么要改变你绑定的属性,而不是让你的视图模型通用化呢? - Mishka
1
如果你想让 ItemsSource 可以从外部进行 绑定,你可以将其公开为用户控件的依赖属性,然后简单地将 LayoutRoot.ItemsSource 绑定到它上面。请参见此答案 - Sinatr
1个回答

1

您只需要使用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>

我们将其数据上下文设置为Self,只是为了本示例的目的。在代码后台,我们定义了一个简单的属性来展示它的工作原理:
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,但原则同样适用于您的情况。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接