I made an example as simple as possible.
I have a class ViewModelMain whose will implement several viewmodels.
I am trying to bind my slider value on a viewmodel in my ViewModelMain.
Here my code:
MainWindow.xaml.cs
I set the datacontext here, don't know if it is realy a good idea.
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
VMMain vm = new VMMain();
this.DataContext = vm;
}
}
MainWindow.xaml
<Window x:Class="WpfApplication1.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>
<Slider Height="23" Name="page_slider" Width="100" Value="{Binding Path=p.NbrLine}" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" Minimum="0" Maximum="10"/>
<TextBox Text="{Binding Value, ElementName=page_slider, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" Height="28" HorizontalAlignment="Stretch" Name="Voiture1Label" VerticalAlignment="Stretch" Margin="0,110,0,172"></TextBox>
</Grid></Window>
ViewModelMain.cs
ViewModelBase : the class which implement the INotifyPropertyChanged
ModelPage : my model
MyPage : my sub viewmode which is the viewmodel of ModelPage
ViewModelMain : my final viewmodel which will implement more viewmodel
public class ViewModelBase : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged(string propName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propName));
}
}
}
public class ModelPage
{
public int NbrLine { get; set; }
public int NbrCapsLock { get; set; }
}
public class MyPage : ViewModelBase
{
private ModelPage _model;
public MyPage(ModelPage m)
{
_model = m;
}
public int NbrLine
{
get { return (_model.NbrLine); }
set
{
if (_model.NbrLine == value) return;
_model.NbrLine = value;
OnPropertyChanged("NbrLine");
}
}
public int NbrCapsLock
{
get { return (_model.NbrCapsLock); }
set
{
if (_model.NbrCapsLock == value) return;
_model.NbrCapsLock = value;
OnPropertyChanged("NbrCapsLock");
}
}
}
public class ViewModelMain
{
public MyPage p;
public ViewModelMain()
{
p = new MyPage(new ModelPage(){NbrLine = 5, NbrCapsLock = 1});
}
}
when i launch it, my slider is still on 0 doesn't understand why it is not on 5.
p is a field, not a property. You should only bind to properties:
public MyPage p { get; set; }
Actually you chould transform p into property like that. WPF can not bind to simple attributes.
public class ViewModelMain
{
public MyPage p { get; set; }
public ViewModelMain()
{
p = new MyPage(new ModelPage() { NbrLine = 5, NbrCapsLock = 1 });
}
}
Related
Is there a way to put a Page inside a <Grid/>, <StackPanel/>, <ContentControl/> or <ScrollViewer/> as content from code using a constructor call?
I expect such things:
XAML:
<Grid>
<ScrollViewer Content="{Binding Panel0}"/>
</Grid>
C#:
public class TestWindowViewModel : Page
{
public string Name { get; private set; }
public string Description { get; private set; }
public TestWindowViewModel(string name, string description)
{
Name = name;
Description = description;
}
}
_
public partial class SomeViewModel : Page
{
public TestWindowViewModel Panel0;
public SomeViewModel()
{
Panel0 = new TestWindowViewModel("panelName", "panelDescription");
InitializeComponent();
}
}
You can use a Frame tag
<ScrollViewer>
<Frame content = "{Binding MyPage}"/>
</ScrollViewer>
If you don't want to have a prop in your ViewModel then you should be able to do
<ScrollViewer>
<Frame>
<Frame.Content>
<locals:MyPage>
</Frame.Content>
</ScrollViewer>
Keep in mind you have something called TestWindowViewModel and it inherits Page. This is not a ViewModel. Instead it is a normal page.
You want something that looks like this:
public class NotifyPropertyClass : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
private void NotifyPropertyChanged([CallerMemberName] string propertyName = "")
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
private Page myPage;
public Page MyPage
{
get { return myPage; }
set
{
myPage = value;
NotifyPropertyChanged();
}
}
}
and you can go a level farther and make an abstract class:
public abstract class ViewModel : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
private void NotifyPropertyChanged([CallerMemberName] string propertyName = "")
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
and then you can just inherit ViewModel like so:
public class TestWindow: Page
{
public TestWindow()
{
InitializeComponent();
}
}
public class TestWindowViewModel : ViewModel
{
private string name;
public string Name
{
get { return name; }
set
{
name = value;
NotifyPropertyChanged();
}
}
private string description;
public string Description
{
get { return description; }
set
{
Description = value;
NotifyPropertyChanged();
}
}
}
Once you get this all seperated out correctly you can use the frame and do the same for the SomePage and SomePageViewModel and then you can use actual binding on the Frame Content from the ViewModel. I know this is long winded, but if you start out right on setting up a good MVVM setup you will save yourself headache if you ever get into Async and what not.
in xaml:
<ScrollViewer HorizontalScrollBarVisibility="Auto" VerticalScrollBarVisibility="Auto">
<Frame x:Name="CurrentPage" NavigationUIVisibility="Hidden"></Frame>
</ScrollViewer>
in cs:
CurrentPage.Content = content;
where content is Page
I use MVVM when I update view model programmatically view does not update.
public class ViewModelBase : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
public virtual void OnPropertyChanged(string propertyName)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
my model :
public class Payment:ViewModelBase
{
private long _paymentId;
private decimal _price;
[DatabaseGenerated(DatabaseGeneratedOption.None)]
public long PaymentId {
get { return _paymentId; }
set
{
_paymentId = value;
OnPropertyChanged(nameof(PaymentId));
}
}
public decimal Price {
get { return _price; }
set
{
_price = value;
OnPropertyChanged(nameof(Price));
}
}
}
my view model :
class PaymentFactorViewModel : ViewModelBase
{
public PaymentFactorViewModel()
{
PaymentFactor = new PaymentFactor();
PaymentFactor.Price=350,000;
}
private Payment _paymentFactor;
public Payment PaymentFactor
{
get { return _paymentFactor; }
set
{
_paymentFactor = value;
OnPropertyChanged(nameof(PaymentFactor));
}
}
}
my view :
<TextBox x:Name="txtPrice" Text="{Binding PaymentFactor.Price,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged"/>
when I change TextBox.Text ViewModel will update, but when I change ViewModel programmatically View does not update.
For example I set PaymentFactor.Price=350,000 in ViewModel constructor but TextBox.Text is 0.
There are several mistakes in the code you posted.
PaymentFactorViewmodel should be public
Lose the , in 350000
You don't have a PaymentFactor class, you have Payment. I don't see how that piece of code can even compile.
The below works ok for me. Or at least it shows 350000 as I'd expect.
I put everything in the one namespace.
xmlns:local="clr-namespace:WpfApp1"
mc:Ignorable="d"
Title="MainWindow" Height="800" Width="1200">
<Window.DataContext>
<local:PaymentFactorViewModel/>
</Window.DataContext>
<Grid>
<TextBox x:Name="txtPrice" Text="{Binding PaymentFactor.Price,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}"/>
</Grid>
</Window>
public class PaymentFactorViewModel : ViewModelBase
{
public PaymentFactorViewModel()
{
PaymentFactor = new Payment();
PaymentFactor.Price=350000;
}
private Payment _paymentFactor;
public Payment PaymentFactor
{
get { return _paymentFactor; }
set
{
_paymentFactor = value;
OnPropertyChanged(nameof(PaymentFactor));
}
}
}
public class Payment:ViewModelBase
{
private long _paymentId;
private decimal _price;
public long PaymentId {
get { return _paymentId; }
set
{
_paymentId = value;
OnPropertyChanged(nameof(PaymentId));
}
}
public decimal Price {
get { return _price; }
set
{
_price = value;
OnPropertyChanged(nameof(Price));
}
}
}
I have been trying to figure out these past 2 days how to switch between 2 User Controls back and forward with buttons inside those User Controls.
I managed to make this happen but with the buttons outside those User Controls.
This is how my project files look
BaseCommand.cs
public class BaseCommand : ICommand
{
private Action<object> _method;
public event EventHandler CanExecuteChanged;
public BaseCommand(Action<object> method)
{
_method = method;
}
public bool CanExecute(object parameter)
{
return true;
}
public void Execute(object parameter)
{
_method.Invoke(parameter);
}
}
MainViewModel.cs
class MainViewModel : INotifyPropertyChanged
{
public ICommand LogInCommand { get; set; }
public ICommand SetupCommand { get; set; }
private object selectedViewModel;
public object SelectedViewModel
{
get { return selectedViewModel; }
set { selectedViewModel = value; OnPropertyChanged("SelectedViewModel"); }
}
public MainViewModel()
{
LogInCommand = new BaseCommand(OpenLogIn);
SetupCommand = new BaseCommand(OpenSetup);
}
private void OpenLogIn(object obj)
{
SelectedViewModel = new LogInViewModel();
}
private void OpenSetup(object obj)
{
SelectedViewModel = new SetupViewModel();
}
public event PropertyChangedEventHandler PropertyChanged;
private void OnPropertyChanged(string propName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propName));
}
}
}
MainWindow.xaml
<StackPanel>
<ContentControl Content="{Binding SelectedViewModel}"/>
<Button Content="Open LogIn" Height="24" Command="{Binding LogInCommand}"/>
<Button Content="Open Setup" Height="24" Command="{Binding SetupCommand}"/>
</StackPanel>
MainWindow.xaml.cs
public MainWindow()
{
InitializeComponent();
this.DataContext = new MainViewModel();
}
LoginViewModel and SetupViewModel are empty classes and their corresponding views have a text block indicating what they are.
What I want is to have instead 2 buttons in my MainWindow.xaml I want 1 in my LogInView.xaml that opens SetupView.xaml and vice versa.
App.xaml
<Application.Resources>
<DataTemplate DataType="{x:Type viewmodels:LogInViewModel}">
<views:LogInView/>
</DataTemplate>
<DataTemplate DataType="{x:Type viewmodels:SetupViewModel}">
<views:SetupView/>
</DataTemplate>
</Application.Resources>
Move "Open Setup" button to LogInView and "Open LogIn" button to SetupView.
In LogInViewModel create SetupCommand and pass the MainViewModel in the ctor. When the button "Open Setup" is clicked and SetupCommand is invoked then call new OpenSetup method on the MainViewModel.
public class LogInViewModel : INotifyPropertyChanged // etc.
{
private readonly MainViewModel mainViewModel;
public ICommand SetupCommand { get; set; }
public LogInViewModel(MainViewModel mainViewModel)
{
this.mainViewModel = mainViewModel;
SetupCommand = new BaseCommand(OpenSetup);
}
private void OpenSetup(object obj)
{
mainViewModel.OpenSetup();
}
....
}
Similar for SetupViewModel
public class SetupViewModel : INotifyPropertyChanged // etc.
{
private readonly MainViewModel mainViewModel;
public ICommand LogInCommand { get; set; }
public SetupViewModel(MainViewModel mainViewModel)
{
this.mainViewModel = mainViewModel;
LogInCommand = new BaseCommand(OpenLogIn);
}
private void OpenLogIn(object obj)
{
mainViewModel.OpenLogIn();
}
....
}
Finally, remove commands from MainViewModel, modify OpenLogIn and OpenSetup methods and pass reference to the MainViewModel when you create new instance of LogInViewModel or SetupViewModel.
public class MainViewModel : INotifyPropertyChanged
{
private object selectedViewModel;
public object SelectedViewModel
{
get { return selectedViewModel; }
set { selectedViewModel = value; OnPropertyChanged("SelectedViewModel"); }
}
public MainViewModel()
{
OpenLogIn();
}
public void OpenLogIn()
{
SelectedViewModel = new LogInViewModel(this);
}
public void OpenSetup()
{
SelectedViewModel = new SetupViewModel(this);
}
public event PropertyChangedEventHandler PropertyChanged;
private void OnPropertyChanged(string propName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propName));
}
}
}
I'm binding a List of a custom class (which implements the INotifyPropertyChanged) into a ListBox.
When I add any item to the List, the ListBox doesn't update, but if I scroll, the ListBox gets updated.
The class
class MyClass : INotifyPropertyChanged
{
private string name = string.Empty;
public string Name { /* INotifyPropertyChanged */ }
}
The property
private List<MyClass> loaded;
public List<MyClass> Loaded { /* INorutyPropertyChanged */ }
The ListBox
<ListBox ItemsSource={Binding Loaded} />
If I force override the List property, it works fine:
Loaded = new List<MyClass>() { new MyClass { Name = "test"; } }
Update to:
public ObservableCollection<MyClass> Loaded { get; private set; }
and
<ListBox ItemsSource={Binding Loaded, UpdateSourceTrigger=PropertyChanged} />
Also, you do not need to use INotiftyPropertyChanged for your Loaded property. If the binding happens once, and the data-source does not change, there's no need.
Edit:
Here's a working example.
MainWindow.xaml
<Window x:Class="WpfApplication3.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
Title="MainWindow" Height="350" Width="525">
<Grid>
<ListBox Width="200" ItemsSource="{Binding Items, UpdateSourceTrigger=PropertyChanged}">
<ListBox.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding Value}"/>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
<Button Width="100" Height="75" HorizontalAlignment="Right" Content="Add" Command="{Binding AddItem}"/>
</Grid>
</Window>
MainWindow.xaml.cs
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
DataContext = new DataContext();
}
}
DataContext.cs
namespace WpfApplication3
{
public class DataContext
{
public ObservableCollection<Item> Items { get; private set; }
public ICommand AddItem { get; private set; }
public DataContext()
{
Items = new ObservableCollection<Item>
{
new Item
{
Value = "test"
}
};
AddItem = new RelayCommand(() =>
{
Items.Add(new Item
{
Value = "new item"
});
}, () => true);
}
}
public class Item
{
public string Value { get; set; }
}
}
RelayCommand.cs
public class RelayCommand : ICommand
{
public event EventHandler CanExecuteChanged
{
add { CommandManager.RequerySuggested += value; }
remove { CommandManager.RequerySuggested -= value; }
}
private Action methodToExecute;
private Func<bool> canExecuteEvaluator;
public RelayCommand(Action methodToExecute, Func<bool> canExecuteEvaluator)
{
this.methodToExecute = methodToExecute;
this.canExecuteEvaluator = canExecuteEvaluator;
}
public RelayCommand(Action methodToExecute)
: this(methodToExecute, null)
{
}
public bool CanExecute(object parameter)
{
if (this.canExecuteEvaluator == null)
{
return true;
}
else
{
bool result = this.canExecuteEvaluator.Invoke();
return result;
}
}
public void Execute(object parameter)
{
this.methodToExecute.Invoke();
}
}
Let me know if you have any questions.
The code below creates two list boxes. When an item in the first list box is selected, I am trying to select the corresponding item in the second list box when there is a match between NameOne and NameTwo. However, it does not select my item in the second list box. Why is that?
XAML:
<Window x:Class="ListBoxTesting.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>
<Grid.RowDefinitions>
<RowDefinition Height="*"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<ListBox Name="ListBoxOne" Grid.Row="0" ItemsSource="{Binding ListOne}" SelectedItem="{Binding SelectedTypeOne}" DisplayMemberPath="NameOne"/>
<ListBox Name="ListBoxTwo" Grid.Row="1" ItemsSource="{Binding ListTwo}" SelectedItem="{Binding SelectedTypeTwo}" DisplayMemberPath="NameTwo"/>
</Grid>
</Window>
Code:
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public class TypeOne : INotifyPropertyChanged
{
public string NameOne { get; set; }
public TypeOne(string name)
{
NameOne = name;
}
public event PropertyChangedEventHandler PropertyChanged;
public void NotifyPropertyChanged(string property)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(property));
}
}
}
public class TypeTwo : INotifyPropertyChanged
{
public string NameTwo { get; set; }
public TypeTwo(string name)
{
NameTwo = name;
}
public event PropertyChangedEventHandler PropertyChanged;
public void NotifyPropertyChanged(string property)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(property));
}
}
}
TypeOne m_SelectedTypeOne;
public TypeOne SelectedTypeOne
{
get
{
return m_SelectedTypeOne;
}
set
{
m_SelectedTypeOne = value;
SelectedTypeOne.NotifyPropertyChanged("NameOne");
foreach (TypeTwo typeTwo in ListTwo)
{
if (typeTwo.NameTwo == value.NameOne)
{
SelectedTypeTwo = typeTwo;
}
}
}
}
TypeTwo m_SelectedTypeTwo;
public TypeTwo SelectedTypeTwo
{
get
{
return m_SelectedTypeTwo;
}
set
{
m_SelectedTypeTwo = value;
SelectedTypeTwo.NotifyPropertyChanged("NameTwo");
}
}
public List<TypeOne> ListOne { get; set; }
public List<TypeTwo> ListTwo { get; set; }
public MainWindow()
{
InitializeComponent();
DataContext = this;
ListOne = new List<TypeOne>();
ListOne.Add(new TypeOne("Mike"));
ListOne.Add(new TypeOne("Bobby"));
ListOne.Add(new TypeOne("Joe"));
ListTwo = new List<TypeTwo>();
ListTwo.Add(new TypeTwo("Mike"));
ListTwo.Add(new TypeTwo("Bobby"));
ListTwo.Add(new TypeTwo("Joe"));
}
}
Create a "Container" ViewModel which implements INotifyPropertyChanged instead of using the Window itself as a container.
Doing DataContext = this; is not recommended.
public class ViewModel: INotifyPropertyChanged
{
public TypeOne SelectedTypeOne
{
get { return m_SelectedTypeOne; }
set
{
m_SelectedTypeOne = value;
NotifyPropertyChanged("SelectedTypeOne");
//foreach (TypeTwo typeTwo in ListTwo)
//{
// if (typeTwo.NameTwo == value.NameOne)
// {
// SelectedTypeTwo = typeTwo;
// }
//}
//these kind of horrible for loops from 500 years ago are not needed in C#. Use proper LINQ:
SelectedTypeTwo = ListTwo.FirstOrDefault(x => x.NameTwo == value.NameOne);
}
}
TypeTwo m_SelectedTypeTwo;
public TypeTwo SelectedTypeTwo
{
get { return m_SelectedTypeTwo; }
set
{
m_SelectedTypeTwo = value;
NotifyPropertyChanged("SelectedTypeTwo");
}
}
}
Then, in the UI:
DataContext = new ViewModel();