2011-05-12 2 views
1

가변 개수의 열을 가진 DataGrid에 일부 데이터를 바인딩해야합니다. 나는 다음과 같은 코드를 사용하여 작업을했다 :WPF : 동적 열을 사용하여 DataGrid 바인딩을 편집하는 방법은 무엇입니까?

int n = 0; 
foreach (string title in TitleList) 
{ 
    DataGridTextColumn col = new DataGridTextColumn(); 
    col.Header = title; 
    Binding binding = new Binding(string.Format("DataList[{0}]", n++)); 
    binding.Mode = BindingMode.TwoWay; 
    col.Binding = binding; 
    grid.Columns.Add(col); 
} 
DataList와 같이 선언

:

public ObservableCollection<double> DataList { get; set; } 

및 TitleList과 같이 선언 :

public ObservableCollection<string> TitleList { get; set; } 

문제는 내가 지정된에도 불구하고 있다는 것입니다 TwoWay 바인딩은 실제로는 단방향입니다. 편집을 시도 할 셀을 클릭하면 예외가 발생합니다. ''EditItem '이 (가)이 뷰에 허용되지 않습니다.' 나는 바인딩 식에서 뭔가를 놓쳤는가?

P. Deborah "Populating a DataGrid with Dynamic Columns in a Silverlight Application using MVVM"에서 기사를 찾았습니다. 그러나 필자는 필자의 경우 (필자는 헤더 바인딩 작업을 할 수 없음) 작업에 어려움을 겪었습니다. 비록 효과가 있었다고하더라도 일관성없는 셀 스타일과 같은 문제에 여전히 직면 해 있습니다. 그래서 위의 코드를 약간 수정하면 효과가 있는지 궁금합니다.

편집 : 내 문제와 관련된 다른 게시물을 발견 : Implicit Two Way binding.

"Two-way binding requires Path or XPath"와 같은 오류가 발생합니다. 그러나 문제는 쉽게 내 문제는 비슷한 방법으로 해결 될 수 있다면 누군가가 나에게 힌트를 줄 수

<TextBox Text="{Binding Path=DataContext, RelativeSource={RelativeSource Self}}"/> 

또는

<TextBox Text="{Binding .}"/> 

를 사용하여 고정 할 수 있는가?

+0

내 답을 편집하면 문제가 귀하의 컬렉션 유형의 이중입니다. – blindmeis

답변

2

인덱서에 바인딩합니까?. DataList Property가 어떻게 보이는지 보여 줄 수 있습니까?

전 색인 속성을 사용하여 이전과 동일했습니다.

public SomeObjectWithIndexer DataList 
{get; set;} 


public class SomeObjectWithIndexer 
{ 
     public string this 
     { 
      get { ... } 
      set { ... }//<-- you need this one for TwoWay 
     } 
} 

편집 : 속성을 편집 할 수없는 이유는 "이중 필드"를 편집하려고했기 때문입니다. 한 가지 해결 방법은 INotifyPropertyChanged를 사용하여 클래스에 랩을 두는 것입니다.

public class DataListItem 
{ 
    public double MyValue { get; set;}//with OnPropertyChanged() and stuff 
} 

다음은

ObservableCollection<DataListItem> 

을 사용할 수 있습니다 당신은 당신의 값을 편집 할 수 있습니다.작업 예 : 단지 보여 양방향 이중에 대한

public class DataItem 
{ 
    public string Name { get; set; } 
    public ObservableCollection<DataListItem> DataList { get; set; } 

    public DataItem() 
    { 
     this.DataList = new ObservableCollection<DataListItem>(); 
    } 
} 

래퍼 노력하고 있습니다 :

public class DataListItem 
{ 
    private double myValue; 
    public double MyValue 
    { 
     get { return myValue; } 
     set { myValue = value; }//<-- set breakpoint here to see that edit is working 
    } 
} 

인덱스 거세한 숫양 질문은 항상 여전히 주위에 같은 숙박 :

Binding binding = new Binding(string.Format("DataList[{0}].MyValue", n++)); 

EDIT2은 DataGrid를 사용한 사용자 정의 컨트롤

<UserControl x:Class="WpfStackoverflow.IndexCollectionDataGrid" 
     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
     xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
     xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
     mc:Ignorable="d" 
     d:DesignHeight="300" d:DesignWidth="300"> 
<DataGrid ItemsSource="{Binding MyList}" AutoGenerateColumns="False"> 
    <DataGrid.Columns> 
     <DataGridTextColumn Header="Name" Binding="{Binding Path=Name}" /> 
     <DataGridTextColumn Header="Index1" Binding="{Binding Path=DataList[0].MyValue, Mode=TwoWay}" /> 
     <DataGridTextColumn Header="Index2" Binding="{Binding Path=DataList[1].MyValue, Mode=TwoWay}" /> 
    </DataGrid.Columns> 
</DataGrid> 
</UserControl> 

.cs

public partial class IndexCollectionDataGrid : UserControl 
{ 
    public IndexCollectionDataGrid() 
    { 
     InitializeComponent(); 
     this.MyList = new ObservableCollection<DataItem>(); 

     var m1 = new DataItem() {Name = "test1"}; 
     m1.DataList.Add(new DataListItem() { MyValue = 10 }); 
     m1.DataList.Add(new DataListItem() { MyValue = 20 }); 

     var m2 = new DataItem() { Name = "test2" }; 
     m2.DataList.Add(new DataListItem() { MyValue = 100 }); 
     m2.DataList.Add(new DataListItem() { MyValue = 200 }); 

     this.MyList.Add(m1); 
     this.MyList.Add(m2); 

     this.DataContext = this; 
    } 

    public ObservableCollection<DataItem> MyList { get; set; } 
} 

이 예제에서는 올바른 방향으로 가보길 바랍니다.

+0

@blindmeis : 답변 해 주셔서 감사합니다. 내 DataList가 ObservableCollection 으로 선언되었습니다. – newman

+0

ObservableCollection의 색인은 항상 동일합니까? – blindmeis

+0

@blindmeis : INotifyChanged가 implemneted 인 객체로 double을 변환하여 제안을 시도했지만 동일한 오류가 발생했습니다. 그래서 인덱서 문제인지 잘 모르겠습니다. – newman

관련 문제