全部 - 尝试做两件事:我有一个简单的应用程序,我正在尝试将我的Viewmodel集合绑定到我的视图。考虑到两种方法,但我两个都陷入困境:
方法1:使用Grid作为容器来绑定textblock属性。
方法2:将对象的属性直接绑定到我视图上的文本块(不使用网格作为容器及其Datacontext属性)
Rule_Model_1.cs
public class Rule_Model_1
{
public string topMessage { get; set; }
public List<string> recipients { get; set; }
public string bottomMessage { get; set; }
public string hypLink { get; set; }
public OCCBlock blockType { get; set; }
public enum OCCBlock
{
HardBlock,
SoftBlock,
ModifyAndSend
}
}
Rule_VM_1.cs
class Rule_VM_1
{
#region Properties
public List<Rule_Model_1> rule { get; set; }
#endregion
#region Constructor
public Rule_VM_1()
{
#region Initializing a Rule
rule = new List<Rule_Model_1>();
rule.Add(new Rule_Model_1()
{
topMessage = "Lorem ipsum dolor sit amet.",
recipients = new List<string> {"pr@hotmail.com", "pra@gmail.com"},
bottomMessage = "Lorem ipsum dolor sit amet",
hypLink = "http://www.abc.com",
blockType = Rule_Model_1.OCCBlock.HardBlock
});
#endregion
}
#endregion
}
Rule_UI.xaml.cs
public partial class Rule_UI_1 : UserControl
{
Rule_VM_1 rulevm1;
public Rule_UI_1()
{
InitializeComponent();
rulevm1 = new Rule_VM_1();
DataContext = rulevm1;
}
}
Rule_UI.xaml
<UserControl x:Class="OCC_WPF_POC.Rule_UI_1"
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">
<GroupBox Header="Rule Details">
<Grid HorizontalAlignment="Center" VerticalAlignment="Center">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto"></ColumnDefinition>
<ColumnDefinition Width="*"></ColumnDefinition>
</Grid.ColumnDefinitions>
<Grid Grid.Column="1" DataContext="{Binding rule}">
<Grid.RowDefinitions>
<RowDefinition Height="50"></RowDefinition>
<RowDefinition Height="200"></RowDefinition>
<RowDefinition Height="50"></RowDefinition>
</Grid.RowDefinitions>
<TextBlock Grid.Row="0" Text="{Binding topmessage}" />
</Grid>
</Grid>
</GroupBox>
该视图仍未显示任何内容。同样如上所述 - 我如何使两种方法都有效?非常感谢任何代码示例
附加图片
答案 0 :(得分:1)
问题是您需要一个列表视图来绑定到集合属性(rule
)。这应该有效:
<ListBox Grid.Column="1" ItemsSource="{Binding rule}">
<ListBox.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding topmessage}" />
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
要绑定到网格,您可以使用索引器DataContext
设置[]
:
<Grid Grid.Column="1" DataContext="{Binding rule[0]}">
<TextBlock Grid.Row="0" Text="{Binding topmessage}" />
</Grid>
没有网格:
<TextBlock Text="{Binding rule[0].topmessage}" />