トップ回答者
DataGrid の binding の指定方法について

質問
-
WPF での DataGrid の扱いを学ぶため、簡単なプログラムを作成しようとしております。
DataGrid に以下のような表を表示することを意図してプログラムを組んでおります。
Numeric | Word
--------+------
1 | one
2 | two
3 | three開発に使用している環境は以下の通りです。
- Windows 8.1 Pro (64 bit)
- Visual Studio Express 2013 Update 3
以下のプログラムを走らせると、DataGrid には何も表示されません。意図した動作をさせるには、どのように修正すればよいのでしょうか。
MainWindow.xaml
<RibbonWindow x:Class="TestApplication1.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:my="clr-namespace:TestApplication1" Title="MainWindow" Height="600" Width="800"> <Grid> <Grid.RowDefinitions> <RowDefinition Height="Auto"/> <RowDefinition Height="*"/> </Grid.RowDefinitions> <Grid.DataContext> <my:TestList/> </Grid.DataContext> <Ribbon Grid.Row="0"> </Ribbon> <DataGrid Grid.Row="1" ItemsSource="{Binding TestDatas}"/> </Grid> </RibbonWindow>
MainWindow.xaml.cs
using System.Windows.Controls.Ribbon; namespace TestApplication1 { public partial class MainWindow : RibbonWindow { public MainWindow() { InitializeComponent(); } } }
TestList.cs
using System.Collections.ObjectModel; namespace TestApplication1 { public class TestList { public readonly ObservableCollection<TestData> TestDatas; public TestList() { this.TestDatas = new ObservableCollection<TestData> { new TestData(1,"one"), new TestData(2,"two"), new TestData(3,"three") }; } } }
TestData.cs
namespace TestApplication1 { public class TestData { public readonly int Numeric; public readonly string Word; public TestData(int numeric, string word) { this.Numeric = numeric; this.Word = word; } } }
- 編集済み DJ_Kaosun 2014年10月2日 4:03
回答
すべての返信
-
なるほど。確かに以下のように修正したら意図したとおりの動作をしました。
TestList.cs
using System.Collections.ObjectModel; namespace TestApplication1 { public class TestList { public ObservableCollection<TestData> TestDatas { get; private set; } public TestList() { this.TestDatas = new ObservableCollection<TestData> { new TestData(1,"one"), new TestData(2,"two"), new TestData(3,"three") }; } } }
TestData.cs
namespace TestApplication1 { public class TestData { public int Numeric { get; private set; } public string Word { get; private set; } public TestData(int numeric, string word) { this.Numeric = numeric; this.Word = word; } } }
フィールドとプロパティは違うものなのですね。
「public int Num;」と「public int Num {get; set;}」、
「public readonly int Num;」と「public int Num {get; private set;}」
は、それぞれ完全に等価で、シンタックス シュガーだと思いこんでおりました。ちゃんと基礎から勉強しないとだめですね。