У меня есть DataGrid. Я хочу привязать его к списку, который находится в другом классе. Могу я сказать следующее?Как связать DataGrid с другим списком классов?
<DataGrid ItemsSource="{Binding AnotherClass.Instance.MyList}">
...
</DataGrid>
У меня есть DataGrid. Я хочу привязать его к списку, который находится в другом классе. Могу я сказать следующее?Как связать DataGrid с другим списком классов?
<DataGrid ItemsSource="{Binding AnotherClass.Instance.MyList}">
...
</DataGrid>
Я думаю, что это должно работать:
<Grid>
<DataGrid x:Name="MyDatagrid" ItemsSource="{Binding Path=MyList, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" CanUserAddRows="False">
</Grid>
И установить ItemsSource programmaticaly:
MyDatagrig.ItemsSource = MyClass.MyList;
Я предлагаю, используя 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"
};
}