【发布时间】:2018-09-07 11:05:28
【问题描述】:
所以我正在创建“卡片”以直观地表示 StackPanel 中的一组对象(我使用列表来保存这些对象):
主窗口 XAML:
<Window /* ... */>
<StackPanel x:Name="Deck" Orientation="Horizontal" />
</Window>
主窗口 C#:
public partial class MainWindow : Window
{
/* ... */
private void OnDataReceived(List<Reading> readings)
{
foreach(Reading r in readings)
{
Deck.Children.Add(new Card
{
Id = r.Id,
Value = r.Value
});
}
}
}
用户控件 XAML:
<UserControl /* ... */ x:Name="crd">
<Label Content="{Binding Path=Id, ElementName=crd}" />
<Label Content="{Binding Path=Value, ElementName=crd} />
</UserControl>
用户控件 C#:
public partial class LoggerRepresentation : UserControl
{
public string Id { get; set; }
public int Value { get; set; }
/* ... */
}
在向Deck.Children 添加一个元素后,它的视觉表示确实会按预期出现在 StackPanel 中。但是,DP 似乎缺少一些东西,因为绑定 Id 和 Value 的标签仍然为空。
(将x:Name="crd" 提供给我的UserControl,然后在绑定中使用它作为ElementName 的想法已从the answer to a seemingly related question 插入,但在这种情况下可能会产生误导。)
【问题讨论】:
-
看起来你正在做的事情就像它曾经在 Windows 编程中那样。你应该检查 MVVM 和 INotifyPropertyChanged 接口。
标签: c# wpf xaml data-binding