Я пытаюсь создать datagrid, где столбцы генерируются динамически (это отлично работает), но я не могу создать привязки для столбцов, которые автоматически обновляются (что-то вроде INotifyPropertyChanged).Не удалось заполнить DataGrid
Динамическое создание столбцов и использование элементов словаря для привязки, которые могут быть изменены/добавлены динамически. В отладочном выпуске визуальной студии ошибок не обнаружено.
Я думаю, что мне действительно не хватает чего-то второстепенного здесь.
При нажатии кнопки не заполняет второй столбец
ViewModel:
class DataGridAttachedPropertyViewModel {
public ObservableCollection<DataGridColumn> ColumnCollection { get; set; }
public ObservableCollection<AttachedPropertyEmployee> SomEmployees { get; set; }
public ICommand myCommand { get; set; }
public DataGridAttachedPropertyViewModel() {
this.ColumnCollection = new ObservableCollection<DataGridColumn>();
DataGridTextColumn tc = new DataGridTextColumn();
tc.Header = "Sample Column";
// tc.Binding = new Binding("name");
Binding forCurrent = new Binding("SimpleDict[f]");
forCurrent.Mode = BindingMode.TwoWay;
tc.Binding = forCurrent;
DataGridTextColumn tt = new DataGridTextColumn();
tt.Header = "Column x";
// tc.Binding = new Binding("name");
Binding forTheCurrent = new Binding("SimpleDict[x]");
forTheCurrent.Mode = BindingMode.TwoWay;
tt.Binding = forTheCurrent;
myCommand = new DelegateCommand(ButtonBase_OnClick);
this.ColumnCollection.Add(tc);
this.SomEmployees = new ObservableCollection<AttachedPropertyEmployee>();
this.SomEmployees.Add(new AttachedPropertyEmployee("Rajat","Norwalk"));
this.SomEmployees.Add(new AttachedPropertyEmployee("Matthew", "Norwalk"));
}
public void ButtonBase_OnClick() {
foreach (var VARIABLE in SomEmployees) {
VARIABLE.SimpleDict["x"] = "x";
}
}
}
AttachedPropertyEmployee.cs
public class AttachedPropertyEmployee : INotifyPropertyChanged {
private Dictionary<string, string> dict;
public Dictionary<string, string> SimpleDict {
get { return this.dict; }
set
{
if (this.dict != value) {
this.dict = value;
this.NotifyPropertyChanged("SimpleDict");
}
}
}
public AttachedPropertyEmployee(string Name, string Address) {
this.SimpleDict = new Dictionary<string, string>();
SimpleDict["f"] ="b";
this.name = Name;
this.address = Address;
}
public string name;
public string address { get; set; }
public event PropertyChangedEventHandler PropertyChanged;
public void NotifyPropertyChanged(string propName) {
if (this.PropertyChanged != null)
this.PropertyChanged(this, new PropertyChangedEventArgs(propName));
}
}
XAML:
<Window x:Class="LearnInteractivity.LearnDataGridAttachedProperty"
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:LearnInteractivity"
mc:Ignorable="d"
Title="LearnDataGridAttachedProperty" Height="300" Width="300">
<!--
Put a datargrid and an attached property and update columns dynamincally.
-->
<StackPanel>
<DataGrid
local:DataGridColumnsBehavior.BindableColumns="{Binding ColumnCollection}"
x:Name="dgg"
AutoGenerateColumns="False"
ItemsSource="{Binding SomEmployees}"></DataGrid>
<Button Content="Populate" Command="{Binding myCommand}"></Button>
</StackPanel>
Вы устанавливаете 'VARIABLE.SimpleDict [" x "] =" x ";', но вы никому не говорите. Когда вы это делаете, события не возникают. 'Словарь' не реализует' INotifyCollectionChanged'. –
Спасибо! Итак, какие изменения могут быть сделаны.Пожалуйста, предложите некоторые DS, которые могут быть использованы/другие способы обхода для моей цели: я хочу иметь возможность динамически добавлять столбцы и, соответственно, сопоставлять некоторые словарные статьи, такие как структура, где я могу добавлять/изменять вещи. – 10101010
Попробуйте 'VARIABLE.NotifyPropertyChanged (« SimpleDict »)' когда вы меняете в нем значение. –