【问题标题】:DataContext and Command in XAML when used together is not workingXAML 中的 DataContext 和 Command 一起使用时不起作用
【发布时间】:2012-10-15 15:19:51
【问题描述】:

我有一个按钮,当我使用 datacontext 和命令时,命令不起作用:

 <Button  DataContext="{Binding horaires}" Style="{StaticResource RefreshAppBarButtonStyle}" AutomationProperties.Name="{Binding HomeAppBarTitle, Converter={StaticResource StringResourceConverter}}"  Command="{Binding RefreshCommand}" ></Button>

当我删除数据上下文并手动设置名称时:

<Button Style="{StaticResource RefreshAppBarButtonStyle}" AutomationProperties.Name="Actualiser"  Command="{Binding RefreshCommand}" ></Button>

可能是什么问题?

最好的问候

【问题讨论】:

  • 你到底想用这个做什么:DataContext="{Binding horaires}" ?
  • 我尝试用它来改变属性:AutomationProperties.Name 用法语写“Actualiser”,用英文写“Refresh”,“HomeAppBarTitle”包含这个值
  • 在您的代码隐藏中是 RefreshCommand 吗?
  • refreshcommand 在我的 viewModel 中:class HorairesViewModel { public HorairesModel horaires { get;放; } 公共 ICommand RefreshCommand { 获取;私人套装; }
  • 绑定你的按钮的DataContext看起来还是很奇怪。

标签: xaml windows-8 microsoft-metro


【解决方案1】:

horaires 是否有一个名为 RefreshCommand 的属性?我猜不是因为你说它可以在没有设置 DataContext 的情况下工作。

您需要删除 DataContext 绑定并更改 AutomationProperties.Name 属性绑定以使用 horaires 前缀,如下所示:

<Button  AutomationProperties.Name="{Binding horaires.HomeAppBarTitle, Converter={StaticResource StringResourceConverter}}"  
         Command="{Binding RefreshCommand}" />

或者使用RelativeSourceElementName 绑定来查找在其DataContext 中包含RefreshCommand 的UI 元素。例如,

<Button  DataContext="{Binding horaires}"
         AutomationProperties.Name="{Binding HomeAppBarTitle, Converter={StaticResource StringResourceConverter}}"  
         Command="{Binding DataContext.RefreshCommand, RelativeSource={RelativeSource AncestorType={x:Type Window}}}" />

就个人而言,我会选择第一个,因为我希望尽可能避免明确设置DataContext。 UI 应该反映其背后的数据,并且手动设置 DataContext 会更改此层次结构。

【讨论】:

  • 是的,horaires 有一个名为 RefreshCommand 的属性。第一个解决方案解决了我的问题。谢谢
猜你喜欢
  • 2023-03-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-04-10
  • 1970-01-01
  • 1970-01-01
  • 2018-09-24
相关资源
最近更新 更多