I am new to WPF. I have a question. I have an organization module:
class Organization : ObservableObject { public string OrganizationName { get; set; } }
I have a ViewModel organization:
class OrganizationViewModel : ObservableObject { int _count = 0; public OrganizationViewModel() { Organization = new Organization {OrganizationName = "New Organization"}; } public Organization Organization { get; set; } public string OrganizationName { get { return Organization.OrganizationName; } set { if(Organization.OrganizationName != value) { Organization.OrganizationName = value; RaisePropertyChanged("OrganizationName"); } } }
And I have a ViewModel of all organizations:
class AllOrganizationsViewModel { private ObservableCollection<OrganizationViewModel> m_organizations = new ObservableCollection<OrganizationViewModel>(); public ObservableCollection<OrganizationViewModel> Organizations { get { return m_organizations; } set { m_organizations = value; } } public AllOrganizationsViewModel() { for(int i = 0; i < 3; ++i) { m_organizations.Add(new OrganizationViewModel()); } } void AddOrganizationNameExecute() { m_organizations.Add(new OrganizationViewModel()); } bool CanAddOrganizationNameExecute() { return true; } public ICommand AddOrganization{get{return new RelayCommand(AddOrganizationNameExecute, CanAddOrganizationNameExecute);}} }
And this is MainWindow.xaml:
<Window x:Class="DataIntegrityChecker.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:local="clr-namespace:DataIntegrityChecker.ViewModels" Title="MainWindow" Height="350" Width="525"> <Window.DataContext> <local:AllOrganizationsViewModel /> </Window.DataContext> <Grid> <Grid.RowDefinitions> <RowDefinition Height="Auto" /> <RowDefinition Height="285*" /> </Grid.RowDefinitions> <Grid.ColumnDefinitions> <ColumnDefinition Width="156" /> <ColumnDefinition Width="347*" /> </Grid.ColumnDefinitions> <Label Content="Organization: " Margin="0,0,44,0" /> <Button Grid.Row="1" Name="UpdateOrganizations" Content="Update Organization Name" Command="{Binding AddOrganization}" Margin="0,0,0,262" HorizontalAlignment="Left" Width="156" /> <ComboBox Grid.Column="1" Grid.Row="1" Height="23" HorizontalAlignment="Left" Name="comboBox1" VerticalAlignment="Top" Width="155" ItemsSource="{Binding Organizations}" /> </Grid> </Window>
Now, what I get in the ComboBox elements is the name of the OrganizationViewModel class, but I need the OrganizationName string. It seems to me that I have a binding to OrganizationName, which is missing, but I can not figure out where to add if (if this is a problem). I suppose I can create a collection of strings with the names of the organizations I need. But in the future I will need more properties in the organization class so that it can work.
I would be grateful for any help
Mentalbrake
source share