[英]Binding different properties within WPF element using different DataContexts
[英]Binding controls to different DataContexts
我遇到一种情况,我想将具有类items
列表和SolidColorBrush
属性的ListBox
绑定到作为ListBox
本身一部分的TextBlock
foreground
。
ListBox
数据来自MyColors
类的User
和SolidColorBrush
属性。但是,我无法同时为它们两个设置DataContexts
。 设置DataContext
两次将覆盖第一个,并且不会填充ListBox
。 请帮忙!
public Page1()
{
this.DataContext = GetUsers();
this.DataContext = textcolor; // <-overrides the previous DataContext
}
背后的代码:
xaml:
<Grid HorizontalAlignment="Left" Height="650" Margin="0,38,0,0" Grid.RowSpan="2" VerticalAlignment="Top" Width="480">
<ListBox x:Name="lstBani1" ItemsSource="{Binding}" >
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Vertical">
<TextBlock x:Name="tb1" Text="{Binding string1}" Foreground="{Binding Path=Brush1, Mode=OneWay}" Width="480"/>
<TextBlock x:Name="tb2" Text="{Binding string2}" Width="480"/>
<TextBlock x:Name="tb3" Text="{Binding string3}" Width="480"/>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</Grid>
CS:
public partial class Page1 : PhoneApplicationPage
{
public Page1()
{
InitializeComponent();
MyColors textcolor = new MyColors();
textcolor.Brush1 = new SolidColorBrush(Colors.Red);
this.DataContext = GetUsers();
this.DataContext = textcolor; // <-overrides the previous DataContext
}
private List<User> GetUsers() {...}
}
public class User
{
public string string1 { get; set; }
public string string2 { get; set; }
public string string3 { get; set; }
}
public class MyColors : INotifyPropertyChanged
{
private SolidColorBrush _Brush1;
public event PropertyChangedEventHandler PropertyChanged;
public SolidColorBrush Brush1
{
get { return _Brush1; }
set
{
_Brush1 = value;
NotifyPropertyChanged("Brush1");
}
}
public void NotifyPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
{
PropertyChanged(this,
new PropertyChangedEventArgs(propertyName));
}
}
}
有很多方法可以实现这一目标。
尽管由于今晚我在办公桌上的时间有限,所以我将以一种杂乱的ViewModel类型的方式进行操作。
而不是尝试将两个对象传递到数据上下文中。 我建议创建通常称为“视图模型”的视图。 如果您不熟悉MVVM模式,则可以在线阅读很多内容。 但是,这是一个很大的模式,我在大部分工作中只使用其中的一小部分。
根据上面的代码,我添加了一个类似于以下内容的类。
public class AViewModel
{
public List<User> Users { get; set; }
public MyColors Colours { get; set; }
}
这是我要作为数据上下文传递的对象,并在将用户和MyColors列表传递给数据上下文之前对其进行了更新。
现在,对于列表框,我可以执行以下操作...
<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>
我将列表框的前景绑定到颜色,然后在TextBlocks的前景DP上使用相对源传递它
我是使用Windows UNI应用程序执行此操作的,我的项目中显示红色文字。 但是,有很多事情可以覆盖这种颜色。 我们可以整夜谈论这个。
希望这对您有所帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.