【发布时间】:2012-09-09 20:05:48
【问题描述】:
全部 -
需要对此问题有所了解。我创建了一个示例项目来隔离我的一个项目的问题。我正在尝试根据模型中的某个值(Int/String/Enum)设置我的边框背景。
我遇到的问题是:
1) 我相信正在设置 DataTrigger 绑定中的源 - 但我仍然收到此错误: 在“对象”“字符串”上找不到 personId 属性。绑定表达式:路径=personId; DataItem='String' (HashCode=1896530089);目标元素是 'Border' (Name='');目标属性是“NoTarget”(类型“对象”)
2) 我在 int(或字符串)上这样做只是为了让这个概念起作用。但实际上我需要使这个 Enum 值。对此的任何建议也会有所帮助。
这里是sn-ps的代码:
Person.cs
public class Person
{
public int personId { get; set; }
public string personName { get; set; }
public Gender personType { get; set; }
public enum Gender
{
Male,
Female
}
}
PersonViewModel.cs
public class PersonViewModel
{
private ObservableCollection<Person> _people;
public ObservableCollection<Person> people
{
get
{
return _people;
}
}
public PersonViewModel()
{
_people = new ObservableCollection<Person>()
{
new Person()
{
personId = 1,
personName = "John",
personType = Person.Gender.Male
},
new Person()
{
personId = 1,
personName = "Mary",
personType = Person.Gender.Female
},
};
}
}
PersonView.xaml.cs
public PersonView()
{
InitializeComponent();
var personvm = new PersonViewModel();
DataContext = personvm;
}
PersonView.xaml
<Window.Resources>
<Style x:Key="BorderGradient" TargetType="{x:Type Border}">
<Style.Triggers>
<DataTrigger Binding="{Binding Source=people, Path=personId}" Value="1">
<Setter Property="Background">
<Setter.Value>
<LinearGradientBrush StartPoint="0.5,0" EndPoint="0.511,0.957">
<GradientStop Color="LightGray" Offset="0.55" />
<GradientStop Color="Black" Offset="1.3" />
</LinearGradientBrush>
</Setter.Value>
</Setter>
</DataTrigger>
<DataTrigger Binding="{Binding Source=people, Path=personId}" Value="2">
<Setter Property="Background">
<Setter.Value>
<LinearGradientBrush StartPoint="0.5,0" EndPoint="0.511,0.957">
<GradientStop Color="LightGray" Offset="0.55" />
<GradientStop Color="Yellow" Offset="1.3" />
</LinearGradientBrush>
</Setter.Value>
</Setter>
</DataTrigger>
</Style.Triggers>
</Style>
</Window.Resources>
<Border CornerRadius="15,15,15,15" Style="{StaticResource BorderGradient}" >
<Grid Width="Auto" MinWidth="750" Height="Auto" MinHeight="600">
<!-- Logic in VM where visibility would be set through VM -->
<StackPanel Grid.Row="0" HorizontalAlignment="Center" VerticalAlignment="Top" Visibility="To be set" >
<loc:MaleView/>
</StackPanel>
<StackPanel Grid.Row="1" HorizontalAlignment="Center" Visibility=" to be set">
<loc:FemaleView />
</StackPanel>
</Grid>
</Border>
【问题讨论】:
-
Patrick,目前还不清楚您要做什么。你能详细说明你期望发生的事情吗?你能说明你是如何绑定到人的 ObservableCollection 的吗?
-
当然。编辑我上面的帖子以显示上面的真实用例
-
Patrick,当 People 集合中的 Person 等于某个值时,您想要更改数据网格包含的边框吗?如果是这种情况,那么你就错了。您需要样式可以绑定到的 PersonViewModel 上的一个属性,该属性指示背景颜色应该改变,或者其他什么。如果您尝试更改数据网格中单行的背景颜色(绑定到 Person),请创建 DataGridRow 样式并以这种方式设置触发器。
-
Michael - 对不起 - 我意识到简化示例以突出问题 - 我可能有错误的上下文。上下文是这样的-每个人都通过用户控件(单数)显示,我想根据人(男性或女性)更改窗口的背景。当然,我将数据网格粘贴在顶部——这意味着所有数据都显示在同一个视图中——情况并非如此。也更新代码
-
“每个人都通过用户控件显示”。因此,您希望代表一个人的每个用户控件的背景颜色都反映该人的性别。用户控件应该具有“Person”的DataContext,对吗?然后将样式复制到用户控件中,并指定绑定到DataContext的来源。
标签: wpf xaml data-binding