我有一个DataGrid。我想将它绑定到另一个类中的List。我可以说以下吗?
<DataGrid ItemsSource="{Binding AnotherClass.Instance.MyList}">
...
</DataGrid>
答案 0 :(得分:0)
我认为这应该有效:
<Grid>
<DataGrid x:Name="MyDatagrid" ItemsSource="{Binding Path=MyList, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" CanUserAddRows="False">
</Grid>
并设置itemsSource programmaticaly:
MyDatagrig.ItemsSource = MyClass.MyList;
答案 1 :(得分:0)
我建议使用MVVM方法。
使用MVVM框架(如Prism,MvvMLight)或自己创建一个用于所有viewmodels注册的类:
Locator.cs
public class Locator
{
public AnotherClass Another
{
get
{
return AnotherClass.Instance;
}
}
}
添加Locator.cs
作为您视图的可用资源,因此您可以将您的媒体资源设置为DataContext
:
MainWindow.xaml
<Window x:Class="DataGridBindingExample.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:DataGridBindingExample"
mc:Ignorable="d"
xmlns:vm="clr-namespace:DataGridBindingExample"
Title="MainWindow" Height="350" Width="525">
<Window.Resources>
<vm:Locator x:Key="Locator" />
</Window.Resources>
<DataGrid DataContext="{Binding Another, Source={StaticResource Locator}}" ItemsSource="{Binding MyList}">
</DataGrid>
</Window>
AnotherClass.cs
public class AnotherClass
{
private static AnotherClass instance;
private AnotherClass() { }
public static AnotherClass Instance
{
get
{
if (instance == null)
{
instance = new AnotherClass();
}
return instance;
}
}
public IList<string> MyList { get; set; } = new List<string>
{
"one",
"three"
};
}