Here is a class with undefined variable that needs to be passed into the WPF window.
public class SelectedVal<T>
{
public T val {get;set;}
}
Window:
public partial class SOMEDialogue : Window
{
public List<SelectedVal<T>> returnlist { get { return FullList; } }
public List<SelectedVal<T>> FullList = new List<SelectedVal<T>>();
public SOMEDialogue (List<SelectedVal<T>> inputVal)
{
InitializeComponent();
}
}
So here is the question, how can I do this properly to get the T and have a global variable set in my WPF?
Edited (code edited too):
The purpose for the WPF is:
A list of SelectedVal<T> input
Display this input in this WPF
Depend on the T type, user can do something about this input
When finished a return List<SelectedVal<T>> returnlist can be
accessed
This is the basic idea I'm describing. Let me know if you hit any snags. I'm guessing that the search text and the min/max int values are properties of the dialog as a whole. I'm also assuming that there may be a mixture of item types in the collection, which may be an assumption too far. Can you clarify that?
Selected value classes
public interface ISelectedVal
{
Object Val { get; set; }
}
public class SelectedVal<T> : ISelectedVal
{
public T Val { get; set; }
object ISelectedVal.Val
{
get => this.Val;
set => this.Val = (T)value;
}
}
public class StringVal : SelectedVal<String>
{
}
public class IntVal : SelectedVal<int>
{
}
Dialog Viewmodel
public class SomeDialogViewModel : ViewModelBase
{
public SomeDialogViewModel(List<ISelectedVal> values)
{
FullList = values;
}
public List<ISelectedVal> FullList { get; set; }
private String _searchText = default(String);
public String SearchText
{
get { return _searchText; }
set
{
if (value != _searchText)
{
_searchText = value;
OnPropertyChanged();
}
}
}
private int _minInt = default(int);
public int MinInt
{
get { return _minInt; }
set
{
if (value != _minInt)
{
_minInt = value;
OnPropertyChanged();
}
}
}
private int _maxInt = default(int);
public int MaxInt
{
get { return _maxInt; }
set
{
if (value != _maxInt)
{
_maxInt = value;
OnPropertyChanged();
}
}
}
}
.xaml.cs
public SOMEDialogue (List<ISelectedVal> inputValues)
{
InitializeComponent();
DataContext = new SomeDialogViewModel(inputValues);
}
XAML
<Window.Resources>
<DataTemplate DataType="{x:Type local:StringVal}">
<StackPanel>
<Label>Value</Label>
<Label Content="{Binding Val}" />
<Label>Search text:</Label>
<TextBox Text="{Binding DataContext.SearchText, RelativeSource={RelativeSource AncestorType=Window}}" />
<!-- Other stuff -->
</StackPanel>
</DataTemplate>
<DataTemplate DataType="{x:Type local:IntVal}">
<StackPanel>
<Label>Value</Label>
<Label Content="{Binding Val}" />
<Label>Min value:</Label>
<TextBox Text="{Binding DataContext.MinIntVal, RelativeSource={RelativeSource AncestorType=Window}}" />
<Label>Max value:</Label>
<TextBox Text="{Binding DataContext.MaxIntVal, RelativeSource={RelativeSource AncestorType=Window}}" />
<!-- Other stuff -->
</StackPanel>
</DataTemplate>
</Window.Resources>
<Grid>
<ItemsControl
ItemsSource="{Binding FullList}"
/>
</Grid>
Related
I am attempting to prevent my application from deleting a view and then creating a new one each time it's navigated around. I have a dashboard that will run a test program, if I select the settings view, then back to the dashboard, it has deleted the running test and initialized a new view. I need to keep the same view instance alive so that the test can continue to run while the user navigates to the settings view and back again but I cant exactly figure out how to successfully do that. I have attempted making the instance static but that doesn't seem to make a difference.
MainViewModel
class MainVM : ViewModelBase
{
private object _currentView;
public object CurrentView
{
get { return _currentView; }
set { _currentView = value; OnPropertyChanged(); }
}
public ICommand DashboardCommand { get; set; }
public ICommand SettingsCommand { get; set; }
public static DashboardVM DashboardInstance { get; } = new DashboardVM();
public static SettingsVM SettingsInstance { get; } = new SettingsVM();
private void Dashboard(object obj) => CurrentView = DashboardInstance;
private void Settings(object obj) => CurrentView = SettingsInstance;
public MainVM()
{
DashboardCommand = new RelayCommand(Dashboard);
SettingsCommand = new RelayCommand(Settings);
// Startup Page
CurrentView = DashboardInstance;
}
}
ViewModelBase
public partial class ViewModelBase : ObservableObject, INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
public void OnPropertyChanged([CallerMemberName] string propName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propName));
}
public void NotifyPropertyChanged(string propName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propName));
}
}
}
MainView - Navigation
<!-- Navigation Panel -->
<Grid HorizontalAlignment="Left" Width="76">
<Border Background="#3D5A8A" CornerRadius="10,0,0,10" />
<StackPanel Height="1200" Width="76">
<!-- Dashboard Button -->
<nav:Button Style="{StaticResource NavButton_Style}"
Command="{Binding DashboardCommand}"
IsChecked="True">
<Grid>
<Image Source="Images/dash_black_50.png"
Style="{StaticResource NavImage_Style}" />
<TextBlock Text="Dashboard"
Style="{StaticResource NavText_Style}" />
</Grid>
</nav:Button>
<!-- Settings Button -->
<nav:Button Style="{StaticResource NavButton_Style}"
Command="{Binding SettingsCommand}">
<Grid>
<Image Source="Images/gear_black_50.png"
Style="{StaticResource NavImage_Style}" />
<TextBlock Text="Settings"
Style="{StaticResource NavText_Style}" />
</Grid>
</nav:Button>
</StackPanel>
</Grid>
DashboardVM
class DashboardVM : ViewModelBase
{
enum TestItemStatus
{
Reset,
Queued,
InProgress,
Pass,
Fail
}
private readonly PageModel _pageModel;
private string _StartButtonText,
_WaveRelayEthernetText;
private bool isTestRunning;
public DashboardVM()
{
_pageModel = new PageModel();
_StartButtonText = "Start Test";
_WaveRelayEthernetText = string.Empty;
StartButtonCommand = new RelayCommand(o => StartButtonClick("StartButton"));
}
#region Text Handlers
public string StartButtonText
{
get { return _StartButtonText; }
set { _StartButtonText = value; NotifyPropertyChanged("StartButtonText"); }
}
public string WaveRelayEthernetText
{
get { return _WaveRelayEthernetText; }
set { _WaveRelayEthernetText = value; NotifyPropertyChanged("WaveRelayEthernetText"); }
}
#endregion
private bool TestRunning
{
get { return isTestRunning; }
set { isTestRunning = value;
if (isTestRunning) { StartButtonText = "Stop Test"; }
else { StartButtonText = "Start Test";
ResetTestItems();
}
NotifyPropertyChanged("TestRunning");
}
}
public ICommand StartButtonCommand { get; set; }
private void StartButtonClick(object sender)
{
if(TestRunning)
{
TestRunning = false;
}
else
{
SetTestItemsToQueued();
MessageBox.Show("Please plug in Tube 1");
// Start program.
TestRunning = true;
WaveRelayEthernetText = TestItemStatusEnumToString(TestItemStatus.InProgress);
}
}
private string TestItemStatusEnumToString(TestItemStatus temp)
{
if (temp == TestItemStatus.Reset) { return string.Empty; }
else if (temp == TestItemStatus.Queued) { return "Queued"; }
else if (temp == TestItemStatus.InProgress) { return "In Progress"; }
else if (temp == TestItemStatus.Pass) { return "Pass"; }
else if (temp == TestItemStatus.Fail) { return "Fail"; }
else { return string.Empty; }
}
private void SetTestItemsToQueued()
{
WaveRelayEthernetText = TestItemStatusEnumToString(TestItemStatus.Queued);
}
private void ResetTestItems()
{
WaveRelayEthernetText = TestItemStatusEnumToString(TestItemStatus.Reset);
}
}
Image for reference:
My Issue was in the App.xaml, I link a DataTemplate file like this:
<ResourceDictionary Source="Utilities/DataTemplate.xaml" />
Inside the data template, I had this code that linked the views to the view models.
<ResourceDictionary [...]">
<DataTemplate DataType="{x:Type vm:DashboardVM}">
<view:Dashboard />
</DataTemplate>
<DataTemplate DataType="{x:Type vm:SettingsVM}">
<view:Settings />
</DataTemplate>
</ResourceDictionary>
I changed that code to link the two to this:
<ResourceDictionary [...]>
<view:Dashboard x:Key="DashboardViewKey"/>
<view:Settings x:Key="SettingsViewKey"/>
<DataTemplate DataType="{x:Type vm:DashboardVM}">
<ContentControl Content="{StaticResource DashboardViewKey}" />
</DataTemplate>
<DataTemplate DataType="{x:Type vm:SettingsVM}">
<ContentControl Content="{StaticResource SettingsViewKey}" />
</DataTemplate>
</ResourceDictionary>
I am now receiveing the expected behavior of being able to navigate without the Dashboard constructor being called, thus the view does not destory and recreate.
I hope someone else finds this useful.
This website has greatly benefited me, but now I have to ask a question of my own.
I am new to C# and MVVM applications..
Now I am building an app with different views, one view is the navigation view which should show other views depending on the navigation buttons. These buttons depend on the entered value in a view.
Example:
There is a navigationView containing a ContentControl and two buttons (nextStep and previousStep). I have put several textboxes in a view (parameterView) and associated model (parameterViewModel) which is displayed in the ContentControl. When all parameters are entered, the user may, by means of a button (nextStep mentioned before), go to the next step/view (checkDataView).
Now the button (in navigationView) must therefore be visible when all parameters are filled in parameterView, and hidden when one parameter is not filled in. The nextStep button should activate another page in the ContentControl.
I can navigate with checkboxes or radio buttons, but only without dependence on values in another viewModel.
What should I do to get the dependency of parameters in another viewModel?
My NavigationView ContentControl and buttons are defined as:
<ContentControl Grid.Row="1"
Grid.ColumnSpan="5"
Content="{Binding CurrentItemView}" />
<Button Grid.Column="0"
Grid.Row="2"
Content="Next Step"
Style="{StaticResource SubMenuButton}"
Visibility="{Binding PreviousStepCommandVisibility}"
Command="{Binding PreviousStepCommand}"/>
<Button Grid.Column="3"
Grid.Row="2"
Content="Previous Step"
Style="{StaticResource SubMenuButton}"
Visibility="{Binding NextStepCommandVisibility}"
Command="{Binding NextStepCommand}"/>
My ViewModel of above View:
namespace SomeApp.MVVM.ViewModel
{
class GenerateMenuViewModel : BaseViewModel
{
public RelayCommand PreviousStepCommand { get; set; }
public RelayCommand NextStepCommand { get; set; }
private Visibility _previousStepCommandVisibility;
public Visibility PreviousStepCommandVisibility
{
get { return _previousStepCommandVisibility; }
set { _previousStepCommandVisibility = value; }
}
private Visibility _nextStepCommandVisibility;
public Visibility NextStepCommandVisibility
{
get { return _nextStepCommandVisibility; }
set { _nextStepCommandVisibility = value; }
}
public SomethingViewModel SomethingVM { get; set; }
private object _currentItemView;
public object CurrentItemView
{
get { return _currentItemView; }
set
{
_currentItemView = value;
OnPropertyChanged();
}
}
public GenerateMenuViewModel()
{
SomethingVM = new SomethingViewModel();
CurrentItemView = SomethingVM;
}
}
}
TextBoxes in View2, which values give dependence to the navigation buttons, are defined as:
<TextBox Text="{Binding Paramater1, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"/>
<TextBox Text="{Binding Paramater2, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"/>
<TextBox Text="{Binding Paramater3, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"/>
The ViewModel which belongs to the above View:
namespace SomeApp.MVVM.ViewModel
{
class View1ViewModel : BaseViewModel
{
public View1ViewModel()
{
}
private string _parameter1;
public string Parameter1
{
get { return _parameter1; }
set { _parameter1 = value; OnPropertyChanged(); }
}
private string _parameter2;
public string Parameter2
{
get { return _parameter2; }
set { _parameter2 = value; OnPropertyChanged(); }
}
private string _parameter3;
public string Parameter3
{
get { return _parameter3; }
set { _parameter3 = value; OnPropertyChanged(); }
}
}
}
The simple way is to add a property in viewModel to indicate that all the parameters are validated and succeeded.
class View1
{
public bool Isvalid { get => !validationResults.Values.Contains(false); }
Dictionary<string, bool> validationResults = new Dictionary<string, bool>
{
{ nameof(Val1), false }
};
string val1 = "";
public string Val1
{
get => val1; set
{
val1 = value;
OnPropertyChanged();
validationResults[nameof(Val1)] = !string.IsNullOrEmpty(value); //Validation goes here
}
}
My scenario: I have a usercontrol consisting of a comboBox, and a TextBox. The comboBox should hold numbers contained in an ObservableCollection.
The task: The numbers in the ObservableCollection represent paths to book-chapters; therefore each chapter is unique. Meaning: if I have chapters 1 - 5, then the first userControl combo should show all chapters 1-5 (whereas one of them is selected randomly), the second userControl combo contains all chapters, but not the one selected in the previous combo, and so on. The textBox is for annotations for the chapters.
What I achieved so far: I have currently no model; just a main viewModel (ItemsViewModel in my case), and a viewModel for my userControl (PathViewModel). Then there is the mainWindow view.
The problem: On my mainWindow I can create several dynamically created userControls. The userControl TextBox is currently bound to a text property, while the index of the comboBox is bound to another property. But I don't know:
- how to gain access to the index, selected item/value of the specifically userControls
- how to react to a comboBox item/index change
Here is my code:
The userControl
<UserControl> <StackPanel Orientation="Horizontal">
<ComboBox x:Name="combo" Margin="10" MinWidth="60" VerticalAlignment="Center" ItemsSource="{Binding AvailableNumbers}" SelectedIndex="{Binding TheIndex}" />
<TextBox Margin="10" MinWidth="120" Text="{Binding TheText, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"/>
</StackPanel>
The MainWindow
<Window>...<Window.DataContext>
<local:ItemsViewModel/>
</Window.DataContext>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition/>
<ColumnDefinition/>
</Grid.ColumnDefinitions>
<StackPanel x:Name="HostPanel">
<ItemsControl ItemsSource="{Binding PathViewModels}">
<ItemsControl.ItemTemplate>
<DataTemplate>
<local:PathControl/>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</StackPanel>
<StackPanel Grid.Column="1">
<Button Command="{Binding UCCreationCommand}" Content="Add User Control" Margin="10"/>
<Button Command="{Binding UCDeletionCommand}" CommandParameter="" Content="Delete User Control" Margin="10"/>
<Button Command="{Binding ReadoutCommand}" Content="Show ITEMS" Margin="10"/>
</StackPanel>
</Grid></Window>
My main ViewModel (called ItemsViewModel)
public class ItemsViewModel : NotifyPropertyChangedBase
{private int _aNumber;
public int ANumber
{
get { return _aNumber; }
set { _aNumber = value;
OnPropertyChanged(ref _aNumber, value);
}
}
public ObservableCollection<PathViewModel> PathViewModels { get; set; } = new
ObservableCollection<PathViewModel>();
public ObservableCollection<int> AllNumbers { get; set; } = new ObservableCollection<int>();
public ItemsViewModel()
{
UCCreationCommand = new CommandDelegateBase(UCCreationExecute, UCCreationCanExecute);
UCDeletionCommand = new CommandDelegateBase(UCDeletionExecute, UCDeletionCanExecute);
ReadoutCommand = new CommandDelegateBase(ReadoutExecute, ReadoutCanExecute);
AllNumbers.Add(1);
AllNumbers.Add(2);
AllNumbers.Add(3);
AllNumbers.Add(4);
AllNumbers.Add(5);
}
private bool ReadoutCanExecute(object paramerter)
{
if (PathViewModels.Count > 0)
{
return true;
}
return false;
}
private void ReadoutExecute(object parameter)
{
//just for testing
}
public ICommand UCCreationCommand { get; set; }
public ICommand UCDeletionCommand { get; set; }
public ICommand ReadoutCommand { get; set; }
private bool UCCreationCanExecute(object paramerter)
{
if (PathViewModels.Count < 8)
{
return true;
}
else
{
return false;
}
}
private void UCCreationExecute(object parameter)
{
PathViewModel p = new PathViewModel();
foreach (int i in AllNumbers)
{
p.AvailableNumbers.Add(i);
}
int rndIndex = 0;
Random rnd = new Random();
//creates a random chapter index
rndIndex = rnd.Next(0, p.AvailableNumbers.Count);
//just explicit for debugging reasons
p.TheIndex = rndIndex;
AllNumbers.RemoveAt(rndIndex);
PathViewModels.Add(p);
}
private bool UCDeletionCanExecute(object paramerter)
{
if (PathViewModels.Count != 0)
{
return true;
}
else
{
return false;
}
}
private void UCDeletionExecute(object parameter)
{
PathViewModel p = new PathViewModel();
int delIndex = PathViewModels.Count - 1;
p = PathViewModels[delIndex];
AllNumbers.Add((int)p.TheValue+1);
PathViewModels.Remove(p);
}
}
And finally my UserControl ViewModel:
public class PathViewModel : NotifyPropertyChangedBase
{
public ObservableCollection<int> AvailableNumbers { get; set; } = new ObservableCollection<int>();
private int _theIndex;
public int TheIndex
{
get { return _theIndex; }
set
{
_theIndex = value;
OnPropertyChanged(ref _theIndex, value);
}
}
private int _theValue;
public int TheValue
{
get { return _theValue; }
set
{
_theValue = value;
OnPropertyChanged(ref _theValue, value);
}
}
private string _theText;
public string TheText
{
get { return _theText; }
set
{
_theText = value;
OnPropertyChanged(ref _theText, value);
}
}
public PathViewModel()
{
}
}
Any hints on how to go on from here would be highly appreaciated.
I'm trying to build a TreeView using MVVM in a WPF App but I don't understand how to handle HierarchicalDataTemplate. My TreeView should represent a folder structure which contains folders within folders and so on.
My folder ViewModel is defined as follows:
public class TreeViewFolderViewModel : ViewModelBase
{
private int _id;
private int _parentId;
private string _text;
private string _key;
private ObservableCollection<TreeViewFolderViewModel> _children;
public int Id
{
get { return this._id; }
set { Set(() => Id, ref this._id, value); }
}
public int ParentId
{
get { return this._parentId; }
set { Set(() => ParentId, ref this._parentId, value); }
}
public string Text
{
get { return this._text; }
set { Set(() => Text, ref this._text, value); }
}
public string Key
{
get { return this._key; }
set { Set(() => Key, ref this._key, value); }
}
public ObservableCollection<TreeViewFolderViewModel> Children
{
get { return this._children ?? (this._children =
new ObservableCollection<TreeViewFolderViewModel>()); }
set { Set(() => Children, ref this._children, value); }
}
}
My model has the same structure as my ViewModel so the final ViewModel is a list of folders that contain child folders and so forth. I'm using recursion to load all these folders and that part is working fine.
Where I'm stuck is on how to define and load this ViewModel into the actual TreeView.
I've read Hierarchical DataBinding in TreeView using MVVM pattern and while I more or less understand what's going on, but each of the levels of the TreeView represent a different object type while my TreeView has only one object type and I'm confused as to how I'm suppose to define this.
The Root ViewModel property in my MainWindowViewModel is of type TreeViewFolderViewModel which means I have a single object which represents to root of my TreeView. This object has Children of type TreeViewFolderViewModel which in turn have also Children of type TreeViewFolderViewModel and so forth
How do I defined this in XAML? I have the following defined:
<TreeView Grid.Row="1" Margin="5,0,5,5" ItemsSource="{Binding RootFolder}"/>
And I've got a Hierarchical template defined as follows:
<Window.Resources>
<HierarchicalDataTemplate ItemsSource="{Binding Children}"
DataType="{x:Type viewmodels:SharePointFolderTreeViewViewModel}">
<Label Content="{Binding Name}"/>
</HierarchicalDataTemplate>
</Window.Resources>
But nothing is loading up.
Any ideas on how I can resolve this?
Thanks.
I prepared a small sample to illustrate.
ViewModels
public class TreeViewFolderViewModel : ViewModelBase
{
private int id;
public int Id
{
get { return id; }
set { id = value; OnPropertyChanged("Id"); }
}
private string text;
public string Text
{
get { return text; }
set { text = value; OnPropertyChanged("Text"); }
}
private ObservableCollection<TreeViewFolderViewModel> children;
public ObservableCollection<TreeViewFolderViewModel> Children
{
get
{
return children ?? (children =
new ObservableCollection<TreeViewFolderViewModel>());
}
set { children = value; OnPropertyChanged("Children"); }
}
}
public class TreeViewModel : ViewModelBase
{
private List<TreeViewFolderViewModel> items;
public List<TreeViewFolderViewModel> Items
{
get { return items; }
set { items = value; OnPropertyChanged("Items"); }
}
public TreeViewModel()
{
Items = new List<TreeViewFolderViewModel>()
{
new TreeViewFolderViewModel()
{
Id =0, Text="RootFolder", Children=new ObservableCollection<TreeViewFolderViewModel>()
{
new TreeViewFolderViewModel() { Id = 10, Text = "FirstFolder", Children=new ObservableCollection<TreeViewFolderViewModel>() { new TreeViewFolderViewModel() { Id = 11, Text = "FirstChild" } } } ,
new TreeViewFolderViewModel() { Id = 20, Text = "SecondFolder", Children = new ObservableCollection<TreeViewFolderViewModel>() { new TreeViewFolderViewModel() { Id = 21, Text = "SecondChild" } } } ,
new TreeViewFolderViewModel() { Id = 30, Text = "ThirdFolder", Children = new ObservableCollection<TreeViewFolderViewModel>() { new TreeViewFolderViewModel() { Id = 31, Text = "ThirdChild" } } }
}
}
};
}
}
public class ViewModelBase : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
protected void OnPropertyChanged(string propName)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propName));
}
}
MainWindow.xaml
<Window x:Class="WpfApp.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:WpfApp"
Title="MainWindow" Height="350" Width="525">
<Window.DataContext>
<local:TreeViewModel />
</Window.DataContext>
<Window.Resources>
<HierarchicalDataTemplate ItemsSource="{Binding Children}"
DataType="{x:Type local:TreeViewFolderViewModel}">
<TextBlock>
<TextBlock.Text>
<MultiBinding StringFormat="{}{0} {1}">
<Binding Path="Id" />
<Binding Path="Text" />
</MultiBinding>
</TextBlock.Text>
</TextBlock>
</HierarchicalDataTemplate>
</Window.Resources>
<Grid>
<TreeView ItemsSource="{Binding Items}" />
</Grid>
</Window>
I am currently attempting to display items from an ObservableCollection(myClass). The class itself just has some public string properties. I know that the collection is being updated from a stream source correctly but for some reason it's not updating the list box with the properties I want it to. It's very likely that my XAML has some error in it:
<Window x:Class="PoSClientWPF.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<Grid Margin="10">
<ListBox x:Name="pumpListBox" ItemsSource="{Binding PumpCollection}" Grid.IsSharedSizeScope="True">
<ListBox.ItemTemplate>
<DataTemplate>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition SharedSizeGroup="ID" />
<ColumnDefinition SharedSizeGroup="State" />
</Grid.ColumnDefinitions>
<TextBlock Margin="2" Text="{Binding pumpID}" Grid.Column="0"/>
<TextBlock Margin="2" Text="{Binding state}" Grid.Column="1"/>
</Grid>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</Grid>
</Window>
From researching other posts about this very error. I've included adding this.DataContext = this; to my MainWindow as well as having:
public ObservableCollection<PumpItem> PumpCollection
{
get { return pumpCollection; }
}
In order to bind the ItemsSource to it. I think there is an error in how I'm declaring the bindings in XAML but I'm not sure. I'm trying to add the properties pumpID and state to the listbox from the class instance.
The class pumpItem is shown below:
public enum pumpState
{
Available,
customerWaiting,
Pumping,
customerPaying
};
public enum fuelSelection
{
Petrol,
Diesel,
LPG,
Hydrogen,
None
};
public class PumpItem
{
public string pumpID;
public double fuelPumped;
public double fuelCost;
public fuelSelection selection;
public pumpState state;
public PumpItem(string _ID)
{
this.pumpID = _ID;
this.fuelPumped = 0;
this.fuelCost = 0;
this.selection = fuelSelection.None;
this.state = pumpState.Available;
}
}
Any pointers or help much appreciated.
You can't bind to fields. Change these to public properties
public class PumpItem
{
private string pumpID;
public string PumpId
{
get
{
return pumpId;
}
set
{
pumpId = value;
}
}
private double fuelPumped;
public double FuelPumped
{
get
{
return fuelPumped;
}
set
{
fuelPumped = value;
}
}
private double fuelCost;
public double FuelCost
{
get
{
return fuelCost;
}
set
{
fuelCost= value;
}
}
public fuelSelection selection;
public fuelSelection Selection
{
get
{
return selection;
}
set
{
selection = value;
}
}
public pumpState state;
public pumpState State
{
get
{
return state;
}
set
{
state = value;
}
}
public PumpItem(string _ID)
{
this.PumpID = _ID;
this.FuelPumped = 0;
this.FuelCost = 0;
this.Selection = fuelSelection.None;
this.State = pumpState.Available;
}
}
XAML
<TextBlock Margin="2" Text="{Binding PumpID}" Grid.Column="0"/>
<TextBlock Margin="2" Text="{Binding State}" Grid.Column="1"/>
Check the Output console for binding errors