如何设置单个控件的DataContext来编写后台代码

时间:2013-07-20 21:30:32

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

如何设置单个控件的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" />

有更好的解决方案吗?

1 个答案:

答案 0 :(得分:0)

将我的评论转换为答案:

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

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

和代码隐藏类的ctor:

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

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

相关问题