【发布时间】:2012-03-07 01:31:37
【问题描述】:
正如标题, 我在 SO 中看到了几个类似的问题 this 或 this,但我没有看到解决方案。
知道是否需要绑定code-beind,需要设置Datacontext = this
但我的问题是我的数据上下文已经绑定到我的 ViewModel,但我想使用代码中定义的 Command 进行一些 UI 操作。
是否可以在 xaml 中绑定它?如果有,怎么做?
编辑:我确实尝试了以下方法:
<Window x:Class="WpfApplication3.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Window1" Height="300" Width="300" x:Name="_Root">
<Grid x:Name="hellogrid">
<TextBlock x:Name="myTextBlock" Text="AAAA"/>
<Button Margin="82,119,121,120" Name="button2" Content="{Binding Path=Text, ElementName=myTextBlock}"/>
<Button Margin="82,72,121,0" Name="button3" Content="{Binding Path=MyText, ElementName=_Root}" Height="23" VerticalAlignment="Top" />
</Grid>
还有代码隐藏:
public partial class Window1 : Window
{
public string MyText { get; set; }
public Window1()
{
InitializeComponent();
MyText = "ABC";
}
}
我可以看到 Button2 显示 AAAA,但 Button3 什么也没显示....
【问题讨论】:
-
请查看我更新的答案,我刚刚测试过,绑定 button3 内容属性的方式工作正常,如果您需要在运行时更改 MyText 属性,您只需要实现更改通知...