私は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>
そしてprogrammaticalyのItemsSourceを設定します。
MyDatagrig.ItemsSource = MyClass.MyList;
を私はMVVMのアプローチを使用してお勧めします。
(プリズム、MvvMLightなど)MVVMフレームワークを使用するか、自分ですべての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"
};
}