我有一些在代码后面实例化的对象,例如,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/