簡單的WPF/XAML問題。在XAML中,我如何在給定的上下文中引用Self/this對象?在一個帶有主窗口,一個控件和窗口的編碼C#屬性的非常基本的應用程序中,我想要將控件的屬性綁定到窗口的手形編碼屬性。在XAML中綁定到Self /'this'
在代碼中,這是很容易 - 在窗口的構造函數,我添加了這個:
Binding bind = new Binding();
bind.Source = this;
bind.Path = new PropertyPath("ButtonWidth");
button1.SetBinding(WidthProperty, bind);
很顯然,我有一個名爲buttonWidth屬性,以及一個名爲button1控件。我無法弄清楚如何在XAML中做到這一點。像下面的例子中各種嘗試都沒有奏效:
<Button x:Name="button1" Width="{Binding Source=Self Path=ButtonWidth}"/>
<Button x:Name="button1" Width="{Binding RelativeSource={RelativeSource Self} Path=ButtonWidth}"/>
等
感謝
非常感謝你這篇文章。這對我幫助很大!我一直在尋找一個3小時的好解決方案。 – 2017-03-17 01:12:32
我有一個DataGrid,如果用戶通過其CommandParameter =「{Binding ElementName = MyDataGrid,Path = SelectedItems}」的InputBinding的KeyBinding訪問其內聯ContextMenu的MenuItem的Command中的一個,它將把SelectedItems傳遞給Bound ICommand。但是,如果通過ContextMenu訪問它,則會傳遞null。我試過CommandParameter =「{Binding SelectedItems}」,「{Binding ElementName = MyDataGrid,Path = SelectedItems}」,「{Binding RelativeSource = {RelativeSource FindAncestor,AncestorType = {x:Type DataGrid}},Path = SelectedItems}」 。我在Command之前設置了CommandParameter。 – Tom 2017-05-08 21:36:24