这是我第一次发布问题。我正在研究这个问题大约一整天,但不明白为什么这个绑定(bind)不起作用。
我想要一个标签来显示对象“热点”的名称,该对象是名为 Plan 的类实例的属性。有多个计划,每个计划包含多个热点。当我点击一个热点时,属性 Plan.SelectedHotSpot
将这个点击的热点设置为值。如果没有选择 HotSpot,它将变为空。
XAML:
<Label Name="lblHotSpotName" />
从 ListBox 中选择 Plan 时的 MainWindow 代码:
private void lstPlans_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
canvas.Plan = PlanBLL.GetPlanByID(plans[lstPlans.SelectedIndex].ID);
lblHotSpotName.DataContext = canvas.Plan;
lblHotSpotName.SetBinding(Label.ContentProperty, "SelectedHotSpot.Name");
}
计划类:
public class Plan : INotifyPropertyChanged
{
private HotSpot selectedHotSpot;
public HotSpot SelectedHotSpot
{
get { return selectedHotSpot; }
set
{
selectedHotSpot = value;
OnPropertyChanged("SelectedHotSpot");
OnPropertyChanged("SelectedHotSpot.Name");
}
}
public event PropertyChangedEventHandler PropertyChanged;
void OnPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
}
当我点击热点时,此代码似乎不起作用 lblHotSpotName
保持为空。
在我看来,加载计划时 SelectedHotSpot 为空,因此它不会绑定(bind)到加载计划后选择的热点对象。
我的暗示对吗?此绑定(bind)需要有一个不为空的现有对象。当对象发生变化时,我们需要再次定义从标签到 Plan.SelectedHotSpot
的绑定(bind)。
感谢您的帮助。
最佳答案
我不能确定我是否完全正确地理解了您的问题,因为您的问题有些不清楚,但是您不能只将数据绑定(bind)到 XAML 中的 Label.Content
属性吗?如果您想要数据绑定(bind)当前在 ListBox
中选择的 Plan
项的 SelectedHotSpot.Name
属性,那么您应该 能够做这样的事情:
<Label Name="lblHotSpotName"
Content="{Binding SelectedItem.SelectedHotSpot.Name, ElementName=lstPlans}" />
更新>>>
您最好还是将 XAML 用于您的Binding
。添加要绑定(bind)的 string
属性,然后在 lstPlans_SelectionChanged
处理程序中更新它:
<Label Name="lblHotSpotName" Content="{Binding SelectedItemHotSpotName}" />
...
private void lstPlans_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
canvas.Plan = PlanBLL.GetPlanByID(plans[lstPlans.SelectedIndex].ID);
SelectedItemHotSpotName = canvas.Plan.SelectedHotSpot.Name;
}
关于c# - 无法绑定(bind)到 DataContext 的属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21957478/