c# - 在代码隐藏中定义的绑定(bind)对象

标签 c# .net wpf binding

我有一些在代码后面实例化的对象,例如,XAML 称为 window.xaml 并且在 window.xaml.cs 中

protected Dictionary<string, myClass> myDictionary;

如何仅使用 XAML 标记将此对象绑定(bind)到 ListView 等?

更新:

(这正是我的测试代码):

<Window x:Class="QuizBee.Host.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="{Binding windowname}" Height="300" Width="300"
    DataContext="{Binding RelativeSource={RelativeSource Self}}">
    <Grid>
    </Grid>
</Window>

代码隐藏

public partial class Window1 : Window
{
    public const string windowname = "ABCDEFG";

    public Window1()
    {
        InitializeComponent();
    }
}

假设标题应该变成“ABCDEFG”对吗?但它最终什么也没显示。

最佳答案

有一种更简单的方法可以做到这一点。您可以为您的 Window 或 UserControl 分配一个名称,然后通过 ElementName 进行绑定(bind)。

Window1.xaml

<Window x:Class="QuizBee.Host.Window1"
        x:Name="Window1"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">

    <ListView ItemsSource="{Binding ElementName=Window1, Path=myDictionary}" />
</Window>

Window1.xaml.cs

public partial class Window1:Window
{
    // the property must be public, and it must have a getter & setter
    public Dictionary<string, myClass> myDictionary { get; set; }

    public Window1()
    {
        // define the dictionary items in the constructor
        // do the defining BEFORE the InitializeComponent();

        myDictionary = new Dictionary<string, myClass>()
        {
            {"item 1", new myClass(1)},
            {"item 2", new myClass(2)},
            {"item 3", new myClass(3)},
            {"item 4", new myClass(4)},
            {"item 5", new myClass(5)},
        }; 

        InitializeComponent();
    }
}

关于c# - 在代码隐藏中定义的绑定(bind)对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1705322/

相关文章:

wpf - IronPython 或 IronRuby 是否非常适合 WPF/Silverlight 中的 MVVM 模式?

C# List<object> 到 Dictionary<key, <object>>

c# - .NET Core 和 PCL 之间有什么区别?

c# - 如何使用类实例、对象或类型锁定 .NET

wpf - 如何将 WPF 大小转换为物理像素?

c# - 将两个属性绑定(bind)到 ==> 单个控件

c# - 使用蓝牙耳机控制WP7和WP8应用

c# - 重启时重置分数

c# - 如何在 C# 中保存并附加到序列化的 MessagePack 二进制文件?

c# - TryParse 一行 : accepted challenge?