繁体   English   中英

将DataContext设置为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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM