why dont show me the data ? WINRT - c#

im try to do a simple excercise, but, when i test the first part (show person data) dont show me nothing into UI.
I checked the bindings and I guess are okay, too, I do a debug in the click event of the button and get all the data, but the UI does not show me anything.
all proyect here: Less_300kb or:
public class Persona: BindableBase
{
private string _nombre;
public string Nombre
{
get { return _nombre; }
set { _nombre = value;
SetProperty(ref _nombre, value);}
}
private string _apellido;
public string Apellido
{
get { return _apellido; }
set { SetProperty(ref _apellido, value); }
}
private int _cedula;
public int Cedula
{
get { return _cedula; }
set { _cedula = value;
SetProperty(ref _cedula, value);}
}
private string _profesion;
public string Profesion
{
get { return _profesion; }
set { SetProperty(ref _profesion, value); }
}
}
the second class
public class GrupoPersonas
{
public string Profesion { get; set; }
public List<Persona> ListaPersonas { get; set; }
}
the Last class
public class DataSourcePersonas
{
//public List<Persona> ListaPersonas { get; set; }
public ObservableCollection<Persona> ListaPersonas { get; set; }
public void CrearLista()
{
var listaPivote = new ObservableCollection<Persona>()
{
new Persona(){ Profesion="Ingeniero",Apellido="Ruiz Pacheco",Nombre="Juan Carlos"},
new Persona(){ Profesion="Médico", Apellido="Gonzalez Ramírez", Nombre="Miguel"},
new Persona(){ Profesion="Analista", Apellido="Ramirez", Nombre="Angel"},
new Persona(){ Profesion="Enfermero",Apellido="Aldana", Nombre="Cesar"},
new Persona(){ Profesion="Conductor",Apellido="Echeverry", Nombre="Andres"},
new Persona(){ Profesion="Piloto", Apellido="Coronel", Nombre="David"},
new Persona(){ Profesion="Capitán", Apellido="Baracaldo", Nombre="Alejandro"},
new Persona(){ Profesion="Biólogo", Apellido="Palacios", Nombre="Mauricio"},
new Persona(){ Profesion="Físico", Apellido="Botía", Nombre="Oscar"},
new Persona(){ Profesion="Astrónomo",Apellido="Heldford", Nombre="Axwell"}
};
Random genCedula = new Random();
var listaFull = from persona in listaPivote
from persona2 in listaPivote
from persona3 in listaPivote
select new Persona()
{
Cedula = (int)(genCedula.NextDouble() * 999999999),
Nombre = persona.Nombre,
Apellido = persona2.Apellido,
Profesion = persona3.Profesion
};
//ListaPersonas = new List<Persona>(listaFull);
ListaPersonas = new ObservableCollection<Persona>(listaFull);
}
public ObservableCollection<GrupoPersonas> ListaPersonasAgrupada { get; set; }
public void CrearGrupo()
{
var lista = from persona in ListaPersonas
group persona by persona.Profesion into grupo
select new GrupoPersonas()
{
Profesion = grupo.Key,
ListaPersonas = grupo.ToList()
};
ListaPersonasAgrupada = new ObservableCollection<GrupoPersonas>(lista);
}
}
the xaml
<Page.Resources>
<data:DataSourcePersonas x:Key="DataSourcePersonas"
x:Name="DataSourcePersonas"></data:DataSourcePersonas>
<CollectionViewSource x:Key="CvsGruposPersonas" x:Name="CvsGruposPersonas" IsSourceGrouped="True"
Source="{Binding Source={StaticResource DataSourcePersonas}, Path=ListaPersonasAgrupada}"
ItemsPath="ListaPersonas"></CollectionViewSource>
</Page.Resources>
GridView x:Name="gvGroup" ItemsSource="{Binding Source={StaticResource DataSourcePersonas}, Path=ListaPersonas}"
Margin="10,113,10,10">
<GridView.ItemTemplate>
<DataTemplate>
<StackPanel Style="{StaticResource apptile}">
<TextBlock Style="{StaticResource PersonName}" Text="{Binding Nombre}"/>
<TextBlock Style="{StaticResource PersonName}" Text="{Binding Apellido}"/>
<TextBlock Style="{StaticResource PersonCedula}" Text="{Binding Cedula}"/>
<TextBlock Style="{StaticResource PersonProfession}" Text="{Binding Profesion}"/>
</StackPanel>
</DataTemplate>
</GridView.ItemTemplate>
</GridView>
MainPage
private void Button_Click(object sender, RoutedEventArgs e)
{
DataSourcePersonas.CrearLista();
DataSourcePersonas.CrearGrupo();
gvGroup.UpdateLayout();
}

Okay, so what's happening is your GridView is getting the ListaPersonasAgrupada, and then you are changing it, but your GridView doesn't know that it was changed.
You need to have your ViewModel tell your GridView that ListaPersonasAgrupada has changed. You can do this with INotifyPropertyChanged. Or, if you're using MvvmLight, you can use RaisePropertyChanged.
The other option is to re-set the ItemsSource of the GridView, but that will break the binding.

Related

Populating a WPF ListBox based on a ComboBox Selection

I am trying to populate a WPF ListBox with data from a SQL Stored Procedure based on a ComboBox Selection. I've gotten the ComboBox to work like its supposed to, but I can't get the ListBox to display any data. My naming might be a little weird, but think of it as: the ComboBox gets all Recipes from SQL and the ListBox needs to display a list of Ingredients and their Amounts based on the users selection from that ComboBox. The API and Stored Procedures(...GetAll() for the ComboBox and GetByRationId() for the ListBox...) work, as I can retrieve the correct data using Swagger in the API and I can Populate the ComboBox and the RationId TextBlock in the UI, but I can't get the ListBox to show any data. I am still new to programming and I'm following tutorials etc. and I can't seem to find anything that speaks to my case specifically. I'm guessing I'm missing something. I've added the aforementioned TextBlock just to display the RationId, which is what needs to be used to get the correct data from SQL, as a test, just to make sure that the Id was getting through...and it is.
Here's the Xaml...
<StackPanel Grid.Column="1" Margin="50" Orientation="Vertical">
<ComboBox x:Name="FeedGroup" MinWidth="300" MinHeight="50"
SelectedItem="{Binding SelectedFeedGroup}">
<ComboBox.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding FeedGroupName}" />
</DataTemplate>
</ComboBox.ItemTemplate>
</ComboBox>
<TextBlock x:Name="SelectedFeedGroup_RationId" Height="81"/>
<ListBox x:Name="FeedGroupRation" MinHeight="200" Padding="20" ItemsSource="{Binding SelectedFeedGroupRation}">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal" Margin="10" HorizontalAlignment="Center">
<TextBlock Text="{Binding CommodityName}" FontSize="20" FontWeight="Bold"
VerticalAlignment="Center" HorizontalAlignment="Center"/>
<TextBlock Text="{Binding CommodityPercentage}" FontSize="16" VerticalAlignment="Center"/>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</StackPanel>
Here is the ViewModel Class...
public class FeedGroupPageViewModel : Screen
{
IFeedGroupEndPoint _feedGroupEndPoint;
IFeedGroupRationEndPoint _feedGroupRationEndPoint;
IMapper _mapper;
private readonly StatusInfoViewModel _status;
private readonly IWindowManager _window;
public FeedGroupPageViewModel(IFeedGroupEndPoint feedGroupEndPoint,
IFeedGroupRationEndPoint feedGroupRationEndpoint,
IConfigHelper configHelper,
IMapper mapper,
StatusInfoViewModel status,
IWindowManager window)
{
_feedGroupEndPoint = feedGroupEndPoint;
_feedGroupRationEndPoint = feedGroupRationEndpoint;
_configHelper = configHelper;
_mapper = mapper;
_status = status;
_window = window;
}
protected override async void OnViewLoaded(object view)
{
base.OnViewLoaded(view);
try
{
await LoadFeedGroup();
}
catch (Exception ex)
{
}
}
private async Task LoadFeedGroup()
{
var FeedGroupList = await _feedGroupEndPoint.GetAll();
var feedGroup = _mapper.Map<List<FeedGroupDisplayModel>>(FeedGroupList);
FeedGroup = new BindableCollection<FeedGroupDisplayModel>(feedGroup);
}
private BindableCollection<FeedGroupDisplayModel> _feedGroup;
public BindableCollection<FeedGroupDisplayModel> FeedGroup
{
get { return _feedGroup; }
set
{
_feedGroup = value;
NotifyOfPropertyChange(() => FeedGroup);
}
}
private FeedGroupDisplayModel _selectedFeedGroup;
public FeedGroupDisplayModel SelectedFeedGroup
{
get { return _selectedFeedGroup; }
set
{
_selectedFeedGroup = value;
NotifyOfPropertyChange(() => SelectedFeedGroup);
}
}
private BindableCollection<FeedGroupRationModel> _feedGroupRation;
public BindableCollection<FeedGroupRationModel> FeedGroupRation
{
get { return _feedGroupRation; }
set
{
_feedGroupRation = value;
NotifyOfPropertyChange(() => FeedGroupRation);
}
}
private BindableCollection<FeedGroupRationModel> _selectedFeedGroupRation;
public BindableCollection<FeedGroupRationModel> SelectedFeedGroupRation
{
get { return _selectedFeedGroupRation; }
set
{
_selectedFeedGroupRation = value;
NotifyOfPropertyChange(() => SelectedFeedGroupRation);
}
}
}
And here are the Model Classes
public class FeedGroupDisplayModel : INotifyPropertyChanged
{
public int Id { get; set; }
public string UserId { get; set; }
public string FeedGroupName { get; set; }
public DateTime CreateDate { get; set; }
public DateTime LastModified { get; set; }
public int RationId { get; set; }
public event PropertyChangedEventHandler PropertyChanged;
public void CallPropertyChanged(string propertyName)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
public class FeedGroupRationModel : INotifyPropertyChanged
{
public int Id { get; set; }
public string UserId { get; set; }
public int RationId { get; set; }
public string RationName { get; set; }
public int CommodityId { get; set; }
public string CommodityName { get; set; }
public int CommodityPercentage { get; set; }
public event PropertyChangedEventHandler PropertyChanged;
public void CallPropertyChanged(string propertyName)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
And Here are My Endpoint Classes
public class FeedGroupEndPoint : IFeedGroupEndPoint
{
private IAPIHelper _apiHelper;
public FeedGroupEndPoint(IAPIHelper apiHelper)
{
_apiHelper = apiHelper;
}
public async Task<List<FeedGroupModel>> GetAll()
{
using (HttpResponseMessage response = await _apiHelper.ApiClient.GetAsync("/api/FeedGroup"))
{
if (response.IsSuccessStatusCode)
{
var result = await response.Content.ReadAsAsync<List<FeedGroupModel>>();
return result;
}
else
{
throw new Exception(response.ReasonPhrase);
}
}
}
}
and
public class FeedGroupRationEndPoint : IFeedGroupRationEndPoint
{
private IAPIHelper _apiHelper;
public FeedGroupRationEndPoint(IAPIHelper apiHelper)
{
_apiHelper = apiHelper;
}
public async Task<List<FeedGroupRationModel>> GetRationById()
{
using (HttpResponseMessage response = await _apiHelper.ApiClient.GetAsync("/api/FeedGroup"))
{
if (response.IsSuccessStatusCode)
{
var result = await response.Content.ReadAsAsync<List<FeedGroupRationModel>>();
return result;
}
else
{
throw new Exception(response.ReasonPhrase);
}
}
}
}
I can add more info if needed. I've been working on this for quite awhile now and I'm just out of ideas. Any help would be greatly appreciated!
Thanks in advance!!
You don't seem to set the FeedGroupRation that the ListBox binds to somewhere.
I guess you want to fetch the items and set the property when the SelectedFeedGroup property is set. You could then hook up an event handler to the PropertyChanged event or override the NotifyOfPropertyChange method. Something like this:
public override async void NotifyOfPropertyChange([CallerMemberName] string propertyName = null)
{
base.NotifyOfPropertyChange(propertyName);
if (propertyName == nameof(FeedGroup))
{
//get the items...
var results = await ...;
//set the source property
FeedGroupRation = results;
}
}
As #Michal Davis comment stated I was missing a method for loading the ration, so I added LoadFeedGroupRation()...
private async Task LoadFeedGroupRation()
{
var _feedGroupRation = await _feedGroupRationEndPoint.GetRation();
var feedGroupRation = _mapper.Map<List<FeedGroupRationDisplayModel>>
(_feedGroupPenList);
FeedGroupRationList = new BindableCollection<FeedGroupRationDisplayModel>
(feedGroupRation);
}
Also based on #EldHasp's comment I updated the SelectedFeedGroup setter...
public FeedGroupDisplayModel SelectedFeedGroup
{
get { return _selectedFeedGroup; }
set
{
_selectedFeedGroup = value;
var FeedGroupRation = LoadFeedGroup
NotifyOfPropertyChange(() => SelectedFeedGroup);
}
}
I Don't know if this was the best way but I worked for my case.

C# datagrid is not updating itemsource when get added

when typing in the textbox and click "Add Employee", i want it to update and display to the datagrid, i've implemented INotifyPropertyChanged and RelayCommand. what am i missing that's not populating the data. thanks in advance
here is my model
public class EmployeeModel
{
public string Name { get; set; }
public int Pedicure { get; set; }
public int Tip { get; set; }
public int Total { get; set; }
}
this is my ViewModel
List<EmployeeModel> employeeModel = new List<EmployeeModel>() { };
private ICommand _addEmployeeCommand;
public ICommand AddEmployeeCommand
{
get
{
return _addEmployeeCommand ?? (_addEmployeeCommand = new RelayCommand(x => { AddNewEmployee(); }));
}
}
public List<EmployeeModel> Employee
{
get { return employeeModel; }
set
{
if(value != employeeModel)
{
employeeModel = value;
OnPropertyChanged("Employee");
}
}
}
private string employeeName;
public string EmployeeName
{
get { return employeeName; }
set
{
if (value != employeeName)
{
employeeName = value;
OnPropertyChanged("EmployeeName");
}
}
}
public void AddNewEmployee()
{
Employee.Add(new EmployeeModel { Name = EmployeeName });
}
here is my View
<TabItem Header="Employee">
<StackPanel Orientation="Vertical">
<DataGrid ItemsSource="{Binding Employee}">
</DataGrid>
<StackPanel Orientation="Horizontal">
<TextBlock Text="Name: "/>
<TextBox Text="{Binding EmployeeName}"
Width="40"
Height="15"
VerticalAlignment="Top"/>
<Button Content="Add"
Command="{Binding AddEmployeeCommand}"
Height="20"
VerticalAlignment="Top"/>
</StackPanel>
</StackPanel>
(I pluralized the name Employee to Employees in this answer for future readers)
The problem is with the Source of the DataGrid
Bear in mind that OnPropertyChanged("Employees") only notifies about the changes made to the Employees and is not responsible for any changes made within Employees.
To be clear, it only works when you do employeeModels = new List<EmployeeModel>()
And won't be called when Employees.Add(employee)
Hopefully WPF has its own ObservableCollection type that will take care of that:
private ObservableCollection<Employee> _employees = new ObservableCollection<Employee>;
public ObservableCollection<Employee> Employees { get { return _employees; } }

WPF: Problems with DataContext and ViewModel

I'm having a problem getting the content to display in my program, and I suspect I messed up something relating to the DataContext. The controls I am using come from an extension called Syncfusion (to display graphs) but it could be any other control displaying these items.
MainWindow.xaml.cs:
public MainWindow()
{
InitializeComponent();
ViewModel _viewModel = new ViewModel();
DataContext = _viewModel;
}
ViewModel.cs
public class ViewModel
{
public ObservableCollection<TotalData> TotalDataColl { get; set; }
public ViewModel()
{
TotalDataColl = new ObservableCollection<TotalData>();
var vm = new ChartViewModel
{
Series = new ObservableCollection<SeriesViewModel>
{
new SeriesViewModel{type="Lemons", Items = new ObservableCollection<ItemViewModel>{new ItemViewModel{source = "January", value = 25}, new ItemViewModel{source = "February", value = 35}}},
new SeriesViewModel{type="Oranges",Items = new ObservableCollection<ItemViewModel>{new ItemViewModel{source = "January", value = 22}, new ItemViewModel{source = "February", value = 36}}}
}
};
}
}
MainWindow.xaml
<Grid>
<local:ExtendedChart ItemsSource="{Binding Series}" Margin="0,-38,0,97">
<local:ExtendedChart.ItemTemplate>
<DataTemplate>
<chart:ColumnSeries ItemsSource="{Binding Items}" DependentValuePath="value" IndependentValuePath="source" Title="{Binding type}" />
</DataTemplate>
</local:ExtendedChart.ItemTemplate>
</local:ExtendedChart>
</Grid>
DataClass.cs
public class ChartViewModel : ObservableObject
{
private ObservableCollection<SeriesViewModel> _series;
public ObservableCollection<SeriesViewModel> Series
{
get
{
return _series;
}
set
{
_series = value;
OnPropertyChanged("Series");
}
}
}
public class SeriesViewModel : ObservableObject
{
private ObservableCollection<ItemViewModel> items;
private string _type;
public string type { get { return _type; } set { _type = value; OnPropertyChanged("_type"); } }
public ObservableCollection<ItemViewModel> Items { get { return items; } set { items = value; OnPropertyChanged("Items"); } }
}
public class ItemViewModel : ObservableObject
{
private string _source;
private double _value;
public string Source { get { return _source;} set { _source = value; OnPropertyChanged("Source"); } }
public double Value { get { return _value; } set { _value = value;OnPropertyChanged("Value"); } }
}
ViewModel
public class ViewModel
{
public ObservableCollection<TotalData> TotalDataColl { get; set; }
public ChartViewModel ChartSeriesViewModel { get; set; }
public ViewModel()
{
TotalDataColl = new ObservableCollection<TotalData>();
ChartSeriesViewModel = new ChartViewModel
{
Series = new ObservableCollection<SeriesViewModel>
{
new SeriesViewModel{type="Lemons", Items = new ObservableCollection<ItemViewModel>{new ItemViewModel{source = "January", value = 25}, new ItemViewModel{source = "February", value = 35}}},
new SeriesViewModel{type="Oranges",Items = new ObservableCollection<ItemViewModel>{new ItemViewModel{source = "January", value = 22}, new ItemViewModel{source = "February", value = 36}}}
}
};
}
}
MainWindow.Xaml
<Grid>
<local:ExtendedChart ItemsSource="{Binding ChartSeriesViewModel.Series}" Margin="0,-38,0,97">
<local:ExtendedChart.ItemTemplate>
<DataTemplate>
<chart:ColumnSeries ItemsSource="{Binding Items}" DependentValuePath="value" IndependentValuePath="source" Title="{Binding type}" />
</DataTemplate>
</local:ExtendedChart.ItemTemplate>
</local:ExtendedChart>
</Grid>

MVVM populating a combobox (WinRT and C#)

I have a ComboBox in my XAML. It is populated with the following code:
PopulateColors.cs
public class PopulateColors
{
public ObservableCollection<ItemsColors> itemsColors { get; set; }
public PopulateColors()
{
this.itemsColors = new ObservableCollection<ItemsColors>();
this.itemsColors.Add(new ItemsColors{ ItemColumn = "Blue", IdItemColumn = 0 });
this.itemsColors.Add(new ItemsColors{ ItemColumn = "Red", IdItemColumn = 1 });
this.itemsColors.Add(new ItemsColors{ ItemColumn = "Pink", IdItemColumn = 2 });
}
}
public class ItemsColors
{
public string ItemColumn { get; set; }
public int IdItemColumn { get; set; }
}
pagedemo.xaml.cs:
ClothingViewModel ClothVM = null;
public pagedemo()
{
this.comboColors.DataContext = new PopulateColors();
}
protected override void OnNavigatedTo(NavigationEventArgs e)
{
ClothVM = new ClothingViewModel();
ClothVM = ClothVM.GetData(1);
this.DataContext = ClothVM ;
navigationHelper.OnNavigatedTo(e);
}
private void SaveButton_Click(object sender, RoutedEventArgs e)
{
string result = ClothVM .Save( ClothVM );
if (result.Contains("OK"))
{
//to do
}
}
pagedemo.xaml (XAML design)
<TextBox x:Name="txtJersey"
Text="{Binding Jersey, Mode=TwoWay}"/>
<ComboBox Name="comboColors"
ItemsSource="{Binding itemsColors}"
DisplayMemberPath="ItemColumn"
SelectedValuePath="ItemColumn"/>
Ok. items are display fine in ComboBox.
QUESTION:
I need to save the selected color in a table of the database, using MVVM pattern. But how? I have this code. But I do not know how to link it with the ComboBox:
Model: Clothing.cs
Public class Clothing
{
public string Color { get; set; }
public string Jersey { get; set; }
}
ViewModel: ClothingViewModel.cs
public class ClothingViewModel : ViewModelBase
{
public string Save (ClothingViewModel cloth)
{
string result = string.Empty;
using (var db = new SQLite.SQLiteConnection(App.DBPath))
{
string change = string.Empty;
try
{
var existing = (db.Table<Clothing>().Where(
c => c.id == 1)).SingleOrDefault();
if (existing!= null)
{
existing.Color = cloth.Color;
existing.Jersey = cloth.Jersey;
int success = db.Update(existing);
}
}
catch
{ }
}
}
private int id = 1;
public int ID
{
get
{ return id; }
set
{
if (id == value)
{ return; }
id= value;
RaisePropertyChanged("ID");
}
}
private string color = string.Empty;
public string Color
{
get
{ return color; }
set
{
if (color == value)
{ return; }
color = value;
isDirty = true;
RaisePropertyChanged("Color");
}
}
private string jersey = string.Empty;
public string Jersey
{
get
{ return jersey; }
set
{
if (jersey == value)
{ return; }
jersey = value;
isDirty = true;
RaisePropertyChanged("Jersey");
}
}
}
Actually, there are plenty of options. Let's demonstrate just a few of them.
1. Use Binding with RelativeSource to find Ancestor with appropriate DataContext
XAML-code:
<!-- Please use Page instead of Window. -->
<Window>
<StackPanel>
<TextBox x:Name="txtJersey"
Text="{Binding Jersey, Mode=TwoWay}"/>
<!-- Use {x:Type Page} instead of {x:Type Window}. -->
<ComboBox Name="comboColors" ItemsSource="{Binding itemsColors}"
DisplayMemberPath="ItemColumn"
SelectedValue="{Binding
RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Window}},
Path=DataContext.Color}"
SelectedValuePath="ItemColumn" />
</StackPanel>
</Window>
2. Use Binding with ElementName to the UI-element with appropriate DataContext
XAML-code:
<StackPanel>
<TextBox x:Name="txtJersey"
Text="{Binding Jersey, Mode=TwoWay}"/>
<ComboBox Name="comboColors" ItemsSource="{Binding itemsColors}"
DisplayMemberPath="ItemColumn"
SelectedValue="{Binding
ElementName=txtJersey,
Path=DataContext.Color}"
SelectedValuePath="ItemColumn" />
</StackPanel>
3. Use "one" ViewModel that contains another ViewModel
public class ClothingViewModel : ViewModelBase
{
private readonly PopulateColors colors = new PopulateColors();
public PopulateColors Colors
{
get { return this.colors; }
}
...
}
Page:
// This is a Page (Window in case of using WPF).
public class ClothingWindow
{
public ClothingWindow()
{
InitializeComponent();
// Note: no need to set the DataContext for the ComboBox.
DataContext = new ClothingViewModel();
}
}
XAML-code:
<StackPanel>
<TextBox Text="{Binding Jersey, Mode=TwoWay}"/>
<ComboBox ItemsSource="{Binding Colors.itemsColors}"
DisplayMemberPath="ItemColumn"
SelectedValue="{Binding Color}"
SelectedValuePath="ItemColumn" />
</StackPanel>
References
Data Binding (WPF), MSDN.
Data Binding in WPF, John Papa, MSDN Magazine.

TreeView item foreground binding MVVM

I am using TreeView to display my data. I want to bind foreground of a tree view item. Here is my code below.
View:
<UserControl.Resources>
<HierarchicalDataTemplate x:Key="TreeViewItem" ItemsSource="{Binding Children}">
<StackPanel Orientation="Horizontal">
<CheckBox Margin="2" IsChecked="{Binding IsChecked, Mode=TwoWay}" Content="{Binding Title}"
Background="{Binding Path=ForegroundColor}" IsThreeState="True"/>
</StackPanel>
</HierarchicalDataTemplate>
</UserControl.Resources>
<Grid>
<TreeView Margin="5, 0, 5, 0" ItemsSource="{Binding GeoGraphixModules}" ItemTemplate="{StaticResource TreeViewItem}" IsEnabled="{Binding TreeViewEnabled}" />
</Grid>
And in my view model
public class SomeTreeViewItem
{
public Collection Children
{
get { return _children; }
}
public Brush ForegroundColor
{
get
{
if (SomeCheck)
return Brushes.Green;
else
return Brushes.Red;
}
}
}
Now when I debug this application 'ForegroundColor' is hit but the application still displays black as foreground for all the child items. What is the problem here?
After trying to create the same error i made the following viewmodel
public class ViewModel
{
private Collection<GeoGraphixModule> _geoGraphixModules;
public ViewModel()
{
_geoGraphixModules = new Collection<GeoGraphixModule>();
_geoGraphixModules.Add(new GeoGraphixModule(){Children = new Collection<Bla>(){new Bla{Children = new Collection<Bla>{new Bla(), new Bla(), new Bla()}}}});
_geoGraphixModules.Add(new GeoGraphixModule(){Children = new Collection<Bla>(){new Bla{Children = new Collection<Bla>{new Bla(), new Bla(), new Bla()}}}});
_geoGraphixModules.Add(new GeoGraphixModule(){Children = new Collection<Bla>(){new Bla{Children = new Collection<Bla>{new Bla(), new Bla(), new Bla()}}}});
_geoGraphixModules.Add(new GeoGraphixModule(){Children = new Collection<Bla>(){new Bla{Children = new Collection<Bla>{new Bla(), new Bla(), new Bla()}}}});
}
public Collection<GeoGraphixModule> GeoGraphixModules
{
get { return _geoGraphixModules; }
set { _geoGraphixModules = value; }
}
}
public class GeoGraphixModule
{
public Brush ForegroundColor
{
get
{
if (SomeCheck())
return Brushes.Green;
return Brushes.Red;
}
}
private bool SomeCheck()
{
Random random = new Random();
int randomNumber = random.Next(0, 100);
if ((randomNumber % 2) == 0)
return true;
return false;
}
private Collection<Bla> _children;
public Collection<Bla> Children { get; set; }
}
public class Bla
{
private bool? _isChecked;
private string _title;
private Collection<Bla> _children;
public bool? IsChecked
{
get { return _isChecked; }
set
{
_isChecked = value;
}
}
public Collection<Bla> Children
{
get { return _children; }
set { _children = value; }
}
public string Title
{
get { return _title; }
set
{
_title = value;
}
}
}
Its very ugly i know but it works for the top level take a loot at the below image

Categories

Resources