I am new to WPF and losing my mind with issues. I have a view, viewmodel and model. I want the user user to fill in some information in the view, press button to confirm and then have a new instance of the model (with the user specified parameters) added to the ObservableCollection and to my local database.
View: (unrelated stuff hidden)
<TextBox DataContext="{DynamicResource RiderequestViewModel}" Margin="15,0,15,0" Grid.Column="1" Grid.Row="1" FontSize="12" Height="25" Text="{Binding Riderequest.Time}"/>
<TextBox DataContext="{DynamicResource RiderequestViewModel}" Margin="15,0,15,0" Grid.Column="1" Grid.Row="2" FontSize="12" Height="25" Text="{Binding Riderequest.LocationFrom}"/>
<TextBox DataContext="{DynamicResource RiderequestViewModel}" Margin="15,0,15,0" Grid.Column="1" Grid.Row="3" FontSize="12" Height="25" Text="{Binding Riderequest.LocationTo}"/>
<Button DataContext="{DynamicResource RiderequestViewModel}" x:Name="nextBtn" Grid.Column="0" Grid.ColumnSpan="2" Grid.Row="5" Content="Verder" Width="150" Foreground="White" Command="{Binding AddRiderequestCommand}" Click="NextBtn_Click"/>
ViewModel RiderequestViewModel:
namespace Drink_n_Drive.ViewModel
{
class RiderequestViewModel: BaseViewModel
{
private Riderequest riderequest;
private ObservableCollection<Riderequest> riderequests;
public ObservableCollection<Riderequest> Riderequests
{
get
{
return riderequests;
}
set
{
riderequests= value;
NotifyPropertyChanged();
}
}
public Riderequest Riderequest
{
get
{
return riderequest;
}
set
{
riderequest= value;
NotifyPropertyChanged();
}
}
public ICommand AddRiderequestCommand { get; set; }
public ICommand ChangeRiderequestCommand { get; set; }
public ICommand DeleteRiderequestCommand { get; set; }
public RiderequestViewModel()
{
LoadRiderequests(); //load existing from DB
LinkCommands(); //Link ICommands with BaseCommands
}
private void LoadRiderequests()
{
RiderequestDataService riderequestDS = new RiderequestDataService();
Riderequests= new ObservableCollection<Riderequests>(riderequestDS .GetRiderequests());
}
private void LinkCommands()
{
AddRiderequestCommand = new BaseCommand(Add);
ChangeRiderequestCommand = new BaseCommand(Update);
DeleteRiderequestCommand = new BaseCommand(Delete);
}
private void Add()
{
RiderequestDataService riderequestDS = new RitaanvraagDataService();
riderequestDS.InsertRiderequest(riderequest); //add single (new) instance to the DB
LoadRiderequests(); //Reload ObservableCollection from DB
}
private void Update()
{
if (SelectedItem != null)
{
RiderequestDataService riderequestDS = new RiderequestDataService();
riderequestDS.UpdateRiderequest(SelectedItem);
LoadRiderequests(); //refresh
}
}
private void Delete()
{
if (SelectedItem != null)
{
RiderequestDataService riderequestDS = new RiderequestDataService();
riderequestDS.DeleteRiderequest(SelectedItem);
LoadRiderequests();
}
}
private Riderequest selectedItem;
public Riderequest SelectedItem
{
get { return selectedItem; }
set
{
selectedItem = value;
NotifyPropertyChanged();
}
}
}
}
Pressing the button simply does nothing and I don't know why. I also have a diffrent page where I want to show a datagrid of all instances in the ObservableCollection like this:
<DataGrid Grid.Row="1" Grid.ColumnSpan="2" Grid.RowSpan="3" DataContext="{DynamicResource RitaanvragenViewModel}" ItemsSource="{Binding Ritaanvragen}" SelectedItem="{Binding SelectedItem}" />
But the grid just shows completly empty. I have added some dummydata to my DB but still doesn't work.
My appologies for the mix of English and Dutch in the code.
I'm not 100% sure about it but i would do something like this:
As for first step I would change the TextBox to look like this:
<TextBox DataContext="{DynamicResource Ritaanvraag}" Margin="15,0,15,0" Grid.Column="1" Grid.Row="1" FontSize="12" Height="25" Text="{Binding Path=Time, Mode=OneWayToSource}"/>
There's no need to pass your ViewModel to it as a DataSource because your View's first few meta-data related lines should already define what ViewModel does it belong to.
When you not specify the type of your binding, it will use a default binding type which depends on the current object. You're using a TextBox now so it will have a TwoWay binding by default.
If you only want to accept data from the user and you don't want to show the data if your model has any then you should use OneWayToSource. (Note: OneWay is a direction between source -> view.)
I would also remove the DataSource from your DataGrid because you already set it's ItemSource:
<DataGrid Grid.Row="1" Grid.ColumnSpan="2" Grid.RowSpan="3" ItemsSource="{Binding Ritaanvragen}" SelectedItem="{Binding SelectedItem}" />
Related
Currently i have an ObservableCollection of MyClass in my Viewmodel. I use the getter of this Collection to fill it from an other Datasource. I can now Display this Data in a Window(Grid) and the correct Data is shown, but when i change the Data the set is not fired(I think it is because not the Collection is changed, only a Element in the Collection). Should i create a Property for every Property of MyClass, so i can react to the changes of a single Value, the Questions i ask myself are:
How do i know what Element is selected at the moment
How to fill the Collection correct when i have a binding to every single item
I also thought of a Event when my Collection is changed, but i am not sure how to implement it right.
public ObservableCollection<MyClass<string>> SelectedParams
{
get
{
//Fill the Collection
}
set
{
//I think here i want to react to changed Textboxvalues in my View
}
}
public class MyClass<T> : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
private T _curValue;
private string _value1;
private string _value2;
public string Value1
{
get
{
return _value1;
}
set
{
if (_value1 != value)
{
_value1 = value;
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(Value1)));
}
}
}
public string Value2
{
get
{
return _value2;
}
set
{
if (_value2 != value)
{
_value2 = value;
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(Value2)));
}
}
}
public T curValue
{
get
{
return _curValue;
}
set
{
_curValue = value;
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(curValue)));
}
}
public MyClass()
{
}
public MyClass(string val1, string val2, T curVal)
{
Value1 = val1;
Value2 = val2;
curValue = curVal;
}
}
The xaml Code looks something like this
<ItemsControl ItemsSource="{Binding SelectedParams}">
<ItemsControl.ItemTemplate>
<DataTemplate>
<Grid HorizontalAlignment="Stretch">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<Label Grid.Column="0" Content="{Binding Value1}"/>
<Label Grid.Column="1" Content="{Binding Value2}"/>
<TextBox Grid.Column="2" Text="{Binding curValue, Mode=TwoWay}"/>
</Grid>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
Edit1: Changed MyClass to INotifyPropertyChanged now the Collection changes internal Values but the Setter is still not called on change of a Value
You need to implement INotifyPropertChanged interface for MyClass and raise the PropertyChanged in setter to notify UI that the property value changed.
How do i know what Element is selected at the moment
If you want support for item selection you have to use an other control. ItemsControl does not support selection.
Use ListView for example. Bind ItemsSource and SelectedItem to your class. Now every time you click on an item, SelectedValue is updated. And if you change SelectedValue from code the UI updates the selected item in the list. You can also bind other controls to SelectedValue like I did with the TextBlock outside the ListView.
View
<StackPanel>
<ListView ItemsSource="{Binding Values}" SelectedItem="{Binding SelectedValue}">
<ListView.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<TextBlock Text="{Binding Path=Item1}" />
<TextBlock Text="=" />
<TextBlock Text="{Binding Path=Item2}" />
</StackPanel>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
<StackPanel Orientation="Horizontal">
<TextBox Text="Selected:" Background="DarkGray" />
<TextBox Text="{Binding SelectedValue.Item1, Mode=OneWay}" Background="DarkGray" />
</StackPanel>
</StackPanel>
Data
public class ListViewBindingViewModel : INotifyPropertyChanged
{
private Tuple<string,int> _selectedValue;
public ObservableCollection<Tuple<string,int>> Values { get; }
public Tuple<string, int> SelectedValue
{
get { return _selectedValue; }
set
{
_selectedValue = value;
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(SelectedValue)));
}
}
public ListViewBindingViewModel()
{
Values = new ObservableCollection<Tuple<string, int>> {Tuple.Create("Dog", 3), Tuple.Create("Cat", 5), Tuple.Create("Rat",1)};
}
}
I have a checklist view that has 2 ScrollViewers. One checklist is for incomplete items, the other is for complete items. They are populated by 2 separate observable collections and bound to by ItemsControls.
The UserControl has a button, when clicked will move that 'check' to the other collection.
Currently the way I have this setup is in the ViewModel that's the DataContext for the UserControl there is a public event that is subscribed to by the main window's VM by using:
((CheckItemVM) ((CheckListItem) cli).DataContext).CompleteChanged += OnCompleteChanged;
where cli is the checklist item.
then the OnCompleteChanged finds the appropriate View object by using:
foreach (object aCheck in Checks)
{
if (aCheck.GetType() != typeof (CheckListItem)) continue;
if (((CheckListItem) aCheck).DataContext == (CheckItemVM) sender)
{
cliToMove = (CheckListItem) aCheck;
break;
}
}
It's pretty obvious this breaks MVVM and I'm looking for a way around it (CheckListItem is the View, and CheckItemVM is it's DataContext ViewModel). Reasoning for the boxed type is I've got another UserControl that will have instances inside both, which are basically section labels, and I need to be able to sort my observable collections where there is an association between the checklistitem to a specific section by name.
This can be done in MVVM using commands, and bindings....
The idea that I propouse here is to create a command in the Windows view model, that manage the check command, and this command to receive the item view model in the params, then manage the the things in the command. I'm going to show you a simple example, using MvvmLight library:
The model:
public class ItemViewModel : ViewModelBase
{
#region Name
public const string NamePropertyName = "Name";
private string _name = null;
public string Name
{
get
{
return _name;
}
set
{
if (_name == value)
{
return;
}
RaisePropertyChanging(NamePropertyName);
_name = value;
RaisePropertyChanged(NamePropertyName);
}
}
#endregion
#region IsChecked
public const string IsCheckedPropertyName = "IsChecked";
private bool _myIsChecked = false;
public bool IsChecked
{
get
{
return _myIsChecked;
}
set
{
if (_myIsChecked == value)
{
return;
}
RaisePropertyChanging(IsCheckedPropertyName);
_myIsChecked = value;
RaisePropertyChanged(IsCheckedPropertyName);
}
}
#endregion
}
A simple model with two property, one for the name (an identifier) and another for the check status.
Now in the Main View Model, (or Windows view model like you want)....
First the Collections, one for the checked items, and another for the unchecked items:
#region UncheckedItems
private ObservableCollection<ItemViewModel> _UncheckedItems;
public ObservableCollection<ItemViewModel> UncheckedItems
{
get { return _UncheckedItems ?? (_UncheckedItems = GetAllUncheckedItems()); }
}
private ObservableCollection<ItemViewModel> GetAllUncheckedItems()
{
var toRet = new ObservableCollection<ItemViewModel>();
foreach (var i in Enumerable.Range(1,10))
{
toRet.Add(new ItemViewModel {Name = string.Format("Name-{0}", i), IsChecked = false});
}
return toRet;
}
#endregion
#region CheckedItems
private ObservableCollection<ItemViewModel> _CheckedItems;
public ObservableCollection<ItemViewModel> CheckedItems
{
get { return _CheckedItems ?? (_CheckedItems = GetAllCheckedItems()); }
}
private ObservableCollection<ItemViewModel> GetAllCheckedItems()
{
var toRet = new ObservableCollection<ItemViewModel>();
foreach (var i in Enumerable.Range(11, 20))
{
toRet.Add(new ItemViewModel { Name = string.Format("Name-{0}", i), IsChecked = true });
}
return toRet;
}
#endregion
And the command:
#region CheckItem
private RelayCommand<ItemViewModel> _CheckItemCommand;
public RelayCommand<ItemViewModel> CheckItemCommand
{
get { return _CheckItemCommand ?? (_CheckItemCommand = new RelayCommand<ItemViewModel>(ExecuteCheckItemCommand, CanExecuteCheckItemCommand)); }
}
private void ExecuteCheckItemCommand(ItemViewModel item)
{
//ComandCode
item.IsChecked = true;
UncheckedItems.Remove(item);
CheckedItems.Add(item);
}
private bool CanExecuteCheckItemCommand(ItemViewModel item)
{
return true;
}
#endregion
The magic here could be in the Data binding, in this case I used command parameter and the FindAncestor binding, check the Data Template:
<DataTemplate x:Key="UncheckedItemDataTemplate">
<Grid>
<StackPanel Orientation="Horizontal">
<TextBlock HorizontalAlignment="Left" TextWrapping="Wrap" Text="{Binding Name}" VerticalAlignment="Top"/>
<CheckBox HorizontalAlignment="Left" VerticalAlignment="Top" IsChecked="{Binding IsChecked}" IsEnabled="False"/>
<Button Content="Check" Width="75" Command="{Binding DataContext.CheckItemCommand, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type local:MainWindow}}}" CommandParameter="{Binding Mode=OneWay}"/>
</StackPanel>
</Grid>
</DataTemplate>
<DataTemplate x:Key="CheckedItemDataTemplate">
<Grid>
<StackPanel Orientation="Horizontal">
<TextBlock HorizontalAlignment="Left" TextWrapping="Wrap" Text="{Binding Name}" VerticalAlignment="Top"/>
<CheckBox HorizontalAlignment="Left" VerticalAlignment="Top" IsChecked="{Binding IsChecked}" IsEnabled="False"/>
</StackPanel>
</Grid>
</DataTemplate>
One data template for checked items, and another for unchecked items. Now the usage, this is simpler:
<ListBox Grid.Row="2" Margin="5" ItemsSource="{Binding UncheckedItems}" ItemTemplate="{DynamicResource UncheckedItemDataTemplate}"/>
<ListBox Grid.Row="2" Margin="5" Grid.Column="1" ItemsSource="{Binding CheckedItems}" ItemTemplate="{DynamicResource CheckedItemDataTemplate}"/>
This is a cleaner solution, hope is helps.
I've got a WPF TextBox with TwoWay binding to a ViewModel property. I also have a ToolBar with a Button. When the Button is clicked, it executes a command on the same ViewModel that will do something with the property the TextBox is bound to.
Unfortunately it looks like the Binding only sends the text back to the binding target when the TextBox loses focus. The Button on the Toolbar however does not take focus when clicked. The upshot being that when the Command executes it does not have the text from the textbox, but rather the last value that was bound.
The Xaml looks like so:
<DockPanel LastChildFill="True" VerticalAlignment="Stretch" HorizontalAlignment="Stretch" >
<ToolBarTray Background="White" DockPanel.Dock="Top">
<ToolBar Band="1" BandIndex="1">
<Button Command="{Binding QueryCommand}">
<Image Source="images\media_play_green.png" />
</Button>
</ToolBar>
</ToolBarTray>
<DataGrid VerticalAlignment="Top" DockPanel.Dock="Top" Height="450" AutoGenerateColumns="True"
ItemsSource="{Binding}" DataContext="{Binding Results}" DataContextChanged="DataGrid_DataContextChanged"/>
<TextBox DockPanel.Dock="Bottom" Text="{Binding Sql, Mode=TwoWay}"
AcceptsReturn="True" AcceptsTab="True" AutoWordSelection="True" TextWrapping="WrapWithOverflow"/>
</DockPanel>
How do I get the TextBox's Text binding to update the ViewModel when the ToolBar button is pressed. There is nothing fancy going on in the ViewModel which looks like so:
public class MainViewModel : ViewModelBase
{
private readonly IMusicDatabase _database;
/// <summary>
/// Initializes a new instance of the MainViewModel class.
/// </summary>
public MainViewModel(IMusicDatabase database)
{
_database = database;
QueryCommand = new RelayCommand(Query);
}
public RelayCommand QueryCommand { get; private set; }
private async Task QueryAndSetResults()
{
Results = await _database.Query(Sql);
}
private void Query()
{
QueryAndSetResults();
}
private IEnumerable<object> _results;
public IEnumerable<object> Results
{
get
{
return _results;
}
private set
{
Set<IEnumerable<object>>("Results", ref _results, value);
}
}
private string _sql = "SELECT * FROM this WHERE JoinedComposers = 'Traditional'";
public string Sql
{
get { return _sql; }
set
{
Set<string>("Sql", ref _sql, value);
}
}
}
You can use the UpdateSourceTrigger property of the binding, setting it to PropertyChanged makes the TextBox refresh the binding every time the text changes, not just when losing focus:
<TextBox DockPanel.Dock="Bottom"
Text="{Binding Sql, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"
AcceptsReturn="True"
AcceptsTab="True"
AutoWordSelection="True"
TextWrapping="WrapWithOverflow"/>
More info at MSDN.
Hi all I have a list view which is filled by an ObservableCollection. Now I want to get the value of the selected item from the list and store it. How I can achieve this?
This is my ViewModel:
public StopViewModel(IGrtrService grtrService)
{
Argument.IsNotNull(() => grtrService);
_grtrService = grtrService;
AllStops = _grtrService.LoadStop();
Stop_Line = _grtrService.LoadLines();
SearchCollection = new Command(OnSearchPressed);
}
public ObservableCollection<Stop> AllStopsCollection // Must be property or DP to be bound!
{
get { return AllStops; }
set
{
if (Equals(value, AllStops)) return;
AllStops = value;
}
}
public Grtr Grtr
{
get { return GetValue<Grtr>(GrtrProperty); }
set { SetValue(GrtrProperty, value); }
}
public static readonly PropertyData GrtrProperty = RegisterProperty("Grtr", typeof(Grtr));
}
And in the XAML file I have the following code:
<catel:StackGrid x:Name="LayoutRoot">
<catel:StackGrid.ColumnDefinitions>
<ColumnDefinition />
</catel:StackGrid.ColumnDefinitions>
<catel:StackGrid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="*" />
</catel:StackGrid.RowDefinitions>
<ToolBarTray Grid.Row="0" VerticalAlignment="Top" Background="Azure">
<ToolBar>
<TextBox Width="150" Text="{Binding Path=SearchValue}" />
<Button Content="Search" Command="{Binding SearchCollection}" />
<Button Content="Pass Object" Command="{Binding SearchCollection}" />
</ToolBar>
</ToolBarTray>
<ListBox Grid.Row="1" ItemsSource="{Binding AllStopsCollection}" SelectedValue="{Binding SelectedStop}" />
</catel:StackGrid>
Since you are using Catel, it will automatically take care of change notifications for your. Just define this property:
public Stop SelectedStop
{
get { return GetValue<Stop>(SelectedStopProperty); }
set { SetValue(SelectedStopProperty, value); }
}
public static readonly PropertyData SelectedStopProperty = RegisterProperty("SelectedStop", typeof(Stop));
It will be set to the value.
Pro tip: if you use Catel.Fody, you can write this:
public Stop SelectedStop { get; set; }
and it will automatically be converted to the final Catel property as written above.
In your ViewModel :
private stop _selectedStop;
public Stop SelectedStop
{
get
{
return _selectedStop;
}
set
{
if (_selectedStop!= value)
_selectedStop = value;
OnPropertyChanged("SelectedStop"); //U should implement this method using INotifyPropertyChanged
}
}
In your Window (XAML) , set the Binding's mode to TwoWay :
<ListBox Grid.Row="1" ItemsSource="{Binding AllStopsCollection}" SelectedValue="{Binding SelectedStop, Mode=twoWay}" />
As I see from comments you just can't figure out how to bind list's selected item to property. So first of all you need to create coresponding property in your view model:
public Stop SelectedStop
{
get
{
return _selectedStop;
}
set
{
if (Equals(value, _selectedStop)) return;
_selectedStop = value;
}
}
Make sure that you implement INotifyPropertyChanged interface and thet your property is raising "OnPropertyChanged" when it's changed.
And for the list box you should set:
<ListBox Grid.Row="1" ItemsSource="{Binding AllStopsCollection}" SelectedValue="{Binding SelectedStop, Mode=TwoWay}" />
I have a class with data:
public class routedata : INotifyPropertyChanged
{
private List<double> distances;
public List<double> Distances
{
get { return this.distances; }
set
{
if (this.distances != value)
{
this.distances = value;
this.onPropertyChanged("Distances");
}
}
}
private List<string> instructions;
public List<string> Instructions
{
get { return this.instructions; }
set
{
if (this.instructions != value)
{
this.instructions = value;
this.onPropertyChanged("Instructions");
}
}
}
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void onPropertyChanged(string property)
{
if (this.PropertyChanged != null)
{
this.PropertyChanged(this, new PropertyChangedEventArgs(property));
}
}
}
I'm trying to bind it to a listview like this:
<GridView Name="routeView" HorizontalAlignment="Left" Height="310" Margin="1025,318,0,0" Grid.Row="1"
VerticalAlignment="Top" Width="340" >
<ListView Name="routeList" Height="300" Width="330" ItemsSource="{Binding routeData}">
<ListView.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<TextBlock Text="{Binding Instructions}"
TextWrapping="Wrap" Width="200"/>
<TextBlock Text="{Binding Distances}"
Margin="10,0,0,0" />
<TextBlock Text="km"/>
</StackPanel>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</GridView>
I have in my c# code behind: routeList.datacontext = this;
but it is still not binding, only one empty row is populated in the listview. I have checked the data and it is all present. Any help would be appreciated thank you.
A ListView takes a single collection as ItemsSource, so if you want to display multiple TextBlocks for each item - you need a collection of objects with multiple text properties to bind to your DataTemplate. In your case a routeData is not a collection. Instead you need to define your item view model, e.g.
public class RoutePoint
{
public double Distance { get; set; }
public string Instruction { get; set; }
}
then you would bind your ListView.ItemSource to a List and in your DataTemplate bind it like that:
<TextBlock Text="{Binding Distance}"/>
<TextBlock Text="{Binding Instruction}"/>
You don't need to use an ObservableCollection if your collection never changes after you bind it to the ListView for the first time (SelectedItem doesn't constitute a change).
If your view is called routeView, shouldn't your DataContext be set to a new instance of routedata? Also, I suggest you use an ObservableCollection<T> for your bindable collections rather than List<T>.