【问题标题】:How to set DataContext of a single control to code the behind如何设置单个控件的DataContext来编码后面
【发布时间】:2013-07-22 23:58:14
【问题描述】:

如何设置单个控件的DataContext来编码后面?
无法使用 Windows 的 DataContext,因为它指向其他内容。
对于单个控件,我想将 DataContext 设置为代码隐藏,但无法弄清楚。
不使用 MVVM。

这不起作用,因为 RelativeSource 出现在 ComboBox 中。

<ComboBox DataContext="{Binding RelativeSource={RelativeSource Self}}" ItemsSource="{Binding Path=Chars}" SelectedItem="{Binding Path=Comma}" Width="40" PresentationTraceSources.TraceLevel="High" />

这是一个页面 - 不是一个窗口

这行得通:

<ComboBox DataContext="{Binding RelativeSource={RelativeSource AncestorType=Page}}" ItemsSource="{Binding Path=Chars}" SelectedItem="{Binding Path=Comma, Mode=TwoWay}" Width="40" PresentationTraceSources.TraceLevel="High" />

有没有更好的解决方案?

【问题讨论】:

  • 你试过给ComboBox一个名字说x:Name="cmBox"并在代码隐藏加载事件中分配DataContext直接Loaded += (sender, args) =&gt; cmBox.DataContext = this;其中this是你的代码隐藏类想设置为ComboBoxDataContext
  • @Viv,如何将您的评论升级为答案,Blam,您能否将此问题标记为已回答,这样人们就不会浪费时间来这里给您答案?

标签: .net wpf data-binding code-behind


【解决方案1】:

将我的评论转换为答案:

由于您没有关注 MVVM,因此您可以直接从您的代码隐藏中给您的 ComboBox 一个名称并为其分配 DataContext

<ComboBox x:Name="cmBox" ... />

在代码隐藏类的ctor中:

Loaded += (sender, args) => cmBox.DataContext = this;

说 ^^,使用 RelativeSource 绑定直接从 xaml 分配 DataContext 没有任何问题,这是我自己更喜欢做的事情(但我确实“尝试”在我的应用程序中遵守 MVVM )。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-31
    • 2019-08-27
    • 2023-03-21
    • 1970-01-01
    • 1970-01-01
    • 2013-05-05
    相关资源
    最近更新 更多