1
Would anyone know how I can Binding a generic list in code Behind?
I had to create my Expanderview by code-Behind and have to Binding a property from my list to a Grid update according to the color I Seto in Viewmodel.
Follow the code below:
private List<InventarioDto> _lstInventario;
public List<InventarioDto> LstInventario
{
get { return _lstInventario; }
set
{
_lstInventario = value;
Deployment.Current.Dispatcher.BeginInvoke(() => RaisePropertyChanged("LstInventario"));
}
My Class:
public class InventarioDto : ObservableObject
{
private string CorField;
[System.Runtime.Serialization.DataMemberAttribute()]
public string Cor
{
get
{
return this.CorField;
}
set
{
if ((object.ReferenceEquals(this.CorField, value) != true))
{
this.CorField = value;
this.RaisePropertyChanged("Cor");
}
}
}
}
}
Load event that loads stackePanel:
public async void LstTreeView_Loaded(object sender, RoutedEventArgs e)
{
try
{
int id = int.Parse(ViewModel.IdLocal);
await ViewModel.GetItensPorLocal(id);
for (int i = 0; i < ViewModel.LstTreeView.Count(); i++)
{
ExpanderView expanderView = new ExpanderView();
expanderView.Header = ViewModel.LstTreeView[i].Itens;
expanderView.FontSize = 26;
long[] result = ViewModel.LstInventario.OrderBy(x => x.NumeroPatrimonio).Where(x => x.Itens == expanderView.Header.ToString()).Select(x => x.NumeroPatrimonio).ToArray();
for (int a = 0; a < result.Length; a++)
{
Grid grid = new Grid();
grid.Name = $"txtTreeView{i}{a}";
InventarioDto model = ViewModel.LstInventario[a];
grid.SetBinding(Grid.BackgroundProperty, new Binding("Cor")
{
Source = model,
UpdateSourceTrigger = UpdateSourceTrigger.Default,
});
TextBlock BlockTreeView = new TextBlock();
BlockTreeView.FontSize = 26;
BlockTreeView.Text = "Nº Patrimônio: " + result[a].ToString();
grid.Children.Add(BlockTreeView);
expanderView.Items.Add(grid);
}
stckTreeView.Children.Add(expanderView);
}
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
My shampoo:
<StackPanel Name="stckTreeView" Loaded="LstTreeView_Loaded">
</StackPanel>
I tested your code and it’s OK. What may be wrong is the value that is in the Color property of your Viewmodel object.Lstinventario[a]. The name of the color should be in English, which works. It actually worked with "Blue" and "Blue"
– user26552
I am setting the value "Blue" and is not working, when I test on a property that is not a List works, just does not work with my list.
– Carlos Ribeiro
What does this grid object have to do with your Listbox? It’s too big to create Listbox to post code?
– user26552
I put the whole code, is a dynamical Expanderview just missing to make this color update in my View
– Carlos Ribeiro