C# 将控件绑定到不同的数据上下文

C# 将控件绑定到不同的数据上下文,c#,wpf,xaml,data-binding,listbox,C#,Wpf,Xaml,Data Binding,Listbox,在这种情况下,我想将一个列表框与类项的列表和SolidColorBrush属性绑定到文本块的前台,该文本块是列表框本身的一部分 ListBox的数据来自类User和类MyColors的SolidColorBrush属性,但是,我无法同时为它们设置dataContext。两次设置DataContext将覆盖第一次设置,并且不会填充ListBox。请帮忙 public Page1() { this.DataContext = GetUsers(); this.

在这种情况下,我想将一个
列表框
与类
项的列表
SolidColorBrush
属性绑定到
文本块
的前台,该文本块是
列表框
本身的一部分

ListBox
的数据来自类
User
和类
MyColors
SolidColorBrush
属性,但是,我无法同时为它们设置
dataContext
。两次设置
DataContext
将覆盖第一次设置,并且不会填充
ListBox
。请帮忙

public Page1()
    {
        this.DataContext = GetUsers();
        this.DataContext = textcolor; // <-overrides the previous DataContext
    }
publicpage1()
{
this.DataContext=GetUsers();

this.DataContext=textcolor;//有很多方法可以实现这一点

尽管今晚我在办公桌上的时间有限,我还是会用一种有点凌乱的ViewModel类型的方式来做

不要试图将两个对象传递到datacontext。我建议您创建一个通常称为视图模型的对象。如果您不熟悉MVVM模式,可以在线阅读很多内容。但是,这是一个很大的模式,我在大部分工作中只使用它的一小部分

基于上面的代码,我添加了一个类,看起来像下面这样

public class AViewModel
{
    public List<User> Users { get; set; }
    public MyColors Colours { get; set; }
}
公共类AViewModel
{
公共列表用户{get;set;}
公共颜色{get;set;}
}
这是我将作为数据上下文传递的对象,并在将其传递到datacontext之前更新用户和myColor列表

现在,对于列表框,我可以这样做

<ListBox ItemsSource="{Binding Users}" Foreground="{Binding Colours.Brush1}">

        <ListBox.ItemTemplate>
            <DataTemplate>
                <StackPanel Orientation="Vertical">
                    <TextBlock x:Name="tb1" Text="{Binding string1}" Foreground="{Binding Foreground, RelativeSource={RelativeSource Mode=TemplatedParent}}" Width="480"/>
                </StackPanel>
            </DataTemplate>
        </ListBox.ItemTemplate>

    </ListBox>

我将列表框的前景绑定到颜色,然后使用文本块前景DP上的相对源传递该颜色

我用一个Windows UNI应用程序做到了这一点,我的项目中显示了红色文本。然而,有很多东西可以覆盖这种颜色。我们可以整晚谈论这个问题


希望这对您有所帮助。

我完全按照您说的做了。我像这样传递对象:
ViewModel model=new ViewModel();model.Colors=new MyColors();model.Colors.Brush1=new solidcolorbush(Colors.Red);model.Users=GetUsers();this.DataContext=model;
将填充列表,但项目的颜色不是红色(仍然是黑色)。我正在使用windows phone 7.1应用程序。如上所述,有几种方法可以做到这一点。鉴于列表框中显示的每个项目的datacontext都是T User。您可以通过该对象引用MyColours,然后直接绑定到它。我知道有点乱。在列表框中,如果您将其前台属性设置为红色,Text更改了吗?如果没有,那么textbox上前台属性的绑定将看不到它。我将画笔直接绑定到textblock,它成功了。谢谢!
public class AViewModel
{
    public List<User> Users { get; set; }
    public MyColors Colours { get; set; }
}
<ListBox ItemsSource="{Binding Users}" Foreground="{Binding Colours.Brush1}">

        <ListBox.ItemTemplate>
            <DataTemplate>
                <StackPanel Orientation="Vertical">
                    <TextBlock x:Name="tb1" Text="{Binding string1}" Foreground="{Binding Foreground, RelativeSource={RelativeSource Mode=TemplatedParent}}" Width="480"/>
                </StackPanel>
            </DataTemplate>
        </ListBox.ItemTemplate>

    </ListBox>