![](/img/trans.png)
[英]Binding a code-behind defined property to a DataContext property in XAML?
[英]Setting the DataContext to the current code-behind object in XAML
我正在嘗試將UserControl的DataContext設置為UserControl的代碼隱藏類。 從代碼隱藏方面來看,這很容易做到:
public partial class OHMDataPage : UserControl
{
public StringList Stuff { get; set; }
public OHMDataPage ()
{
InitializeComponent();
DataContext = this;
}
}
<UserControl xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
x:Class="LCDHardwareMonitor.Pages.OHMDataPage">
<ScrollViewer>
<ListBox ItemsSource="{Binding Stuff}" />
</ScrollViewer>
</UserControl>
但是,我怎樣才能完全從XAML端和UserControl級別執行此操作? 如果我這樣做,它適用於子節點(並從代碼隱藏中刪除DataContext = this;
):
<UserControl xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
x:Class="LCDHardwareMonitor.Pages.OHMDataPage">
<ScrollViewer
DataContext="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=UserControl}}">
<ListBox ItemsSource="{Binding Stuff}" />
</ScrollViewer>
</UserControl>
我真的很想了解如何在UserControl本身上執行此操作。 我希望這可行:
<UserControl xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
x:Class="LCDHardwareMonitor.Pages.OHMDataPage"
DataContext="{Binding RelativeSource={RelativeSource Mode=Self}}">
<ScrollViewer>
<ListBox ItemsSource="{Binding Stuff}" />
</ScrollViewer>
</UserControl>
但事實並非如此。
DataContext="{Binding Mode=OneWay, RelativeSource={RelativeSource Self}}"
應該管用。
但是,如果在調用InitializeComponent()
之前未設置屬性,則WPF綁定機制不知道屬性的值已更改。
為了給你一個快速的想法:
// the binding should work
public StringList Stuff { get; set; }
public Constructor()
{
Stuff = new StringList { "blah", "blah", "foo", "bar" };
InitializeComponent();
}
// the binding won't work
public StringList Stuff { get; set; }
public Constructor()
{
InitializeComponent();
Stuff = new StringList { "blah", "blah", "foo", "bar" };
}
如果您正在使用字符串列表,請考慮使用ObservableCollection
。 這將在添加或刪除項目時通知WPF綁定機制。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.