標題爲 我在SO中看到過幾個類似的問題this或this,但我沒有看到它的解決方案。是否可以在不設置DataContext的情況下綁定代碼隱藏屬性?
我知道,如果我需要綁定到代碼beind,我需要設置Datacontext = this
但我的問題是,我的DataContext已經綁定到我的視圖模型,但我想做一些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 Content屬性正常工作的方法,你只需要實現變更通知,如果你需要更改MYTEXT財產在運行時...... – 2012-02-15 18:40:07