I have a textbox which I need to bind a string to.
<TextBox Name="txtDoc" Margin="5" Text ="{Binding Source={x:Static local:DocumentViewModel.FileText}, Path=FileText}">
The FileText property is changed on a different class:
DocumentViewModel.GetInstance().FileText = File.ReadAllText(document.Path);
The DocumentViewModel is a class with Singleton:
public class DocumentViewModel : INotifyPropertyChanged
{
private static string fileText;
public string FileText
{
get { return fileText; }
set
{
fileText = value; // Call OnPropertyChanged whenever the property is updated
OnPropertyChanged("FileText");
}
}
private void OnPropertyChanged(string filetext)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(filetext));
}
}
public event PropertyChangedEventHandler PropertyChanged = delegate { };
private static DocumentViewModel instance = new DocumentViewModel();
private DocumentViewModel() { }
public static DocumentViewModel GetInstance()
{
return instance;
}
}
I need to be able to change the value of the FileText property and reflect this change in the textbox.
It's not working.
I tried using TextBox as a static property but then the Onp
Try to set the source to your viewmodel instead of the property itself, and set the instance property to public? {Binding Source={x:Static local:DocumentViewModel.instance}, Path=FileText}
Edit: Included a complete example, that working for me:
Xaml:
<Window x:Class="Test.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:Test"
Title="MainWindow" Height="350" Width="525"
Loaded="Window_Loaded">
<TextBox Name="txtDoc" Margin="5"
Text="{Binding Source={x:Static local:DocumentViewModel.Instance}, Path=FileText}" />
</Window>
Code-behind:
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void Window_Loaded(object sender, RoutedEventArgs e)
{
DocumentViewModel.Instance.FileText = "Hello world!";
}
}
public class DocumentViewModel : INotifyPropertyChanged
{
#region Singleton implementation
// Static constructor to create the singleton instance.
static DocumentViewModel()
{
DocumentViewModel.Instance = new DocumentViewModel();
}
public static DocumentViewModel Instance { get; private set; }
#endregion
private static string fileText;
public string FileText
{
get { return fileText; }
set
{
if (fileText != value)
{
fileText = value;
OnPropertyChanged("FileText");
}
}
}
#region INotifyPropertyChanged
private void OnPropertyChanged(string filetext)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(filetext));
}
}
public event PropertyChangedEventHandler PropertyChanged;
#endregion
}
Related
I am struggling with this for a while and I cannot figure it out. I have a button and a textBox. The textBox is linked to a property named: MessageDisplay. I want to be able to access this property and update the textBox in several places. Sadly, the PropertyChanged is null. The weird thing is that if I copy/paste the MessageDisplayModel class into the *MessageViewModel * class, it works ...
here is my code :
XAMLfile :
<Grid>
<Button Command="{Binding DisplayTextCommand}" Name="DisplayTextCommand" Margin="53,72,544.6,286" Width="Auto">Push</Button>
<TextBox Name="MessageDisplay" Text="{Binding MessageDisplay, UpdateSourceTrigger=PropertyChanged, Mode=TwoWay}" />
</Grid>
MessageDisplayModel file
public class MessageDisplayModel : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
private string _message;
public string MessageDisplay
{
get { return _message; }
set
{
this._message = value;
this.OnPropertyChanged("MessageDisplay");
}
}
public void UpdateTextBox(string output)
{
MessageDisplay = output;
}
protected virtual void OnPropertyChanged(string propertyName)
{
PropertyChangedEventHandler handler = this.PropertyChanged;
if (handler != null)
{
var e = new PropertyChangedEventArgs(propertyName);
handler(this, e);
}
}
}//class
MessageViewModel file:
public class MessageViewModel
{
private ICommand _testCommand;
public MessageDisplayModel MessageDisplaySmt = new MessageDisplayModel();
public ICommand DisplayTextCommand
{
get
{
return new DelegateCommand(DisplayMessage);
}
set
{
if (_testCommand == value) return;
_testCommand = value;
}
}
public void DisplayMessage()
{
MessageDisplaySmt.UpdateTextBox("Successfuly downloaded");
}
}//class
MainWindow file
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
MessageDisplay.DataContext = new MessageDisplayModel();
DisplayTextCommand.DataContext = new MessageViewModel();
}
}//class
I update the MessageDisplay property by using the method UpdateTextBox(string). I call this method on the click of the button. When debugging the property gets updated but when time comes to notify the UI that the property has changed, PropertyChangedEventHandler PropertyChanged has its value null ... But if I write something in the textBox, the PropertyChangedEventHandler PropertyChanged gets changed and isn't null anymore. All I want is to be able to change the textBox's property whenever I want and from anywhere I want to.
Thank you
You are using two different instances of MessageDisplayModel. You must use a shared instance.
Also the DisplayTextCommand is implemented "wrong". The set method is redundant as the property's get always returns a new instance of the ICommand.
MessageViewModel.cs
public class MessageViewModel
{
pulic MessageViewModel()
{
}
pulic MessageViewModel(MessageDisplayViewModel messageDisplayViewModel)
{
this.MessageDisplaySmt = messageDisplayViewModel;
}
public void DisplayMessage()
{
this.MessageDisplaySmt.UpdateTextBox("Successfuly downloaded");
}
public MessageDisplayViewModel MessageDisplaySmt { get; set; }
public ICommand DisplayTextCommand { get => new DelegateCommand(DisplayMessage); }
}
MainWindow.xaml.cs
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
// Alternatively use XAML to set the DataContext (see MainWindow.xaml). Would require a parameterless constructor.
this.DataContext = new MessageViewModel(new MessageDisplayViewModel());
}
}
MainWindow.xaml
<Window>
<!--
Alternative DataContext declaration using XAML instead of C#.
Requires a parameterless constructor for both view model objects.
-->
<Window.DataContext>
<MessageViewModel>
<MessageViewModel.MessageDisplaySmt>
<MessageDisplayViewModel />
</MessageViewModel.MessageDisplaySmt>
</MessageViewModel>
</Window.DataContext>
<StackPanel>
<Button Command="{Binding DisplayTextCommand}"
Content="Push" />
<TextBox Text="{Binding MessageDisplaySmt.MessageDisplay}" />
</StackPanel>
</Window>
I'm new to WPF MVVM; so, this is a very simple test program exposing a TextBox update issue. Referring to the code below, checking the CheckBox (Name="view1TextBox1" in View1.xml) invokes the property ViewModel1BoolField1 (ViewModel1.cs) where RunTest (Model1.cs) is called. RunTest then returns a string (ViewModel1.cs). This string is then assigned to the ViewModel1StringField1 property. This is where the issue occurs as the TextBox view1TextBox1 (View.xml) is not updated with the test string "Testing 123". I'm not sure if I'm using "OnPropertyChanged" (ViewModelBase.cs) or the the view1TextBox1 "UpdateSourceTrigger=PropertyChanged" (View1.xml) correctly to update the TextBox. Any insight would be great. Thanks!
<UserControl x:Class="WpfMVVMExample1.View.View1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
mc:Ignorable="d"
d:DesignHeight="300" d:DesignWidth="300">
<StackPanel Orientation="Vertical">
<TextBox Width="100" Height="100" Name="view1TextBox1" TextWrapping="Wrap" AcceptsReturn="True" Text="{Binding ViewModel1StringField1, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"/>
<CheckBox Name="view1CheckBox1" IsChecked="{Binding ViewModel1BoolField1}"/>
</StackPanel>
</UserControl>
namespace WpfMVVMExample1.ViewModel
{
public abstract class ViewModelBase : INotifyPropertyChanged, IDisposable
{
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged(string propertyName)
{
PropertyChangedEventHandler handler = this.PropertyChanged;
if (handler != null)
{
var e = new PropertyChangedEventArgs(propertyName);
handler(this, e);
}
}
public void Dispose()
{
this.OnDispose();
}
protected virtual void OnDispose()
{
}
}
}
namespace WpfMVVMExample1.ViewModel
{
class ViewModel1 : ViewModelBase
{
#region Fields
Model1 _model1;
#endregion
#region Constructors
public ViewModel1()
{
_model1 = new Model1 { Model1StringField1 = "Field1" };
}
#endregion
#region Properties
public Model1 Model1
{
set
{
_model1 = value;
}
get
{
return _model1;
}
}
public string ViewModel1StringField1
{
get
{
return Model1.Model1StringField1;
}
set
{
Model1.Model1StringField1 = value;
OnPropertyChanged(ViewModel1StringField1);
}
}
public bool ViewModel1BoolField1
{
get
{
return Model1.Model1BoolField1;
}
set
{
Model1.Model1BoolField1 = value;
if (value)
{
ViewModel1StringField1 = Model1.RunTest();
}
}
}
#endregion
}
}
namespace WpfMVVMExample1.Model
{
class Model1
{
#region Fields
string _model1StringField1;
bool _model1BoolField1;
#endregion
#region Properties
public string Model1StringField1
{
get
{
return _model1StringField1;
}
set
{
_model1StringField1 = value;
}
}
public bool Model1BoolField1
{
get
{
return _model1BoolField1;
}
set
{
_model1BoolField1 = value;
}
}
#endregion
#region Functions
public string RunTest()
{
return "Testing 123";
}
#endregion
}
}
When you call on property changed you are supposed to pass in the property name that changed. Currently you are passing in the value of the property.
OnPropertyChanged(ViewModel1StringField1); }
Should be
OnPropertyChanged("ViewModel1StringField1"); }
If you look at your ViewModelBase class, you'll see this method signature:
protected virtual void OnPropertyChanged(string propertyName)
The parameter of this method is the name of the property that has changed. However, when you invoke it in your ViewModel1StringField1 setter, you do this:
OnPropertyChanged(ViewModel1StringField1);
Instead of the property name, you're passing in its value, which could be anything the user put in. Instead, you want to do this:
OnPropertyChanged("ViewModel1StringField1");
The downside is that the property name is now string and will not be checked by the compiler when you change the name of the property. So just be careful about that (there are alternative ways of doing this).
I've created a small user control to extend my fun with validation!
The problem is that the validation does not work: IDataErrorInfo.this[] is never called.
Thank you in advance for your help.
Stephan
Here is my code:
<UserControl x:Class="WpfApplication5.TextBoxWithValidation"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
x:Name="TextBoxWithValidationControl">
<Grid>
<StackPanel Orientation="Horizontal">
<TextBox Height="23" Width="120"
Text="{Binding Path=Text,ElementName=TextBoxWithValidationControl, ValidatesOnDataErrors=True, UpdateSourceTrigger=PropertyChanged}">
</TextBox>
</StackPanel>
</Grid>
And the code behind is:
public partial class TextBoxWithValidation
{
public static readonly DependencyProperty TextProperty = DependencyProperty.Register("Text",
typeof (object),
typeof (
TextBoxWithValidation
),
new FrameworkPropertyMetadata
(default(object),
FrameworkPropertyMetadataOptions
.BindsTwoWayByDefault));
public TextBoxWithValidation()
{
InitializeComponent();
}
public object Text
{
get { return GetValue(TextProperty); }
set { SetValue(TextProperty, value); }
}
}
Now I'm using this user control as such:
<local:TextBoxWithValidation Text="{Binding Path=Dummy.MyProperty}" />
And my Dummy entity is defined by:
public class Dummy : INotifyPropertyChanged, IDataErrorInfo
{
private string _myProperty;
public string MyProperty
{
get { return _myProperty; }
set
{
_myProperty = value;
OnPropertyChanged("MyProperty");
}
}
#region IDataErrorInfo Members
public string this[string columnName]
{
get { return "This is an error"; }
}
public string Error { get; private set; }
#endregion
#region INotifyPropertyChanged Members
public event PropertyChangedEventHandler PropertyChanged;
#endregion
protected virtual void OnPropertyChanged(string propertyName)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
handler(this, new PropertyChangedEventArgs(propertyName));
}
}
I'm trying to bind a value down from a Window into a UserControl inside a UserControl. But, for some reason, the inner UserControl never even attempts to bind as far as I can tell.
MainWindow.xaml
<Window x:Class="PdfExample.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" xmlns:my="clr-namespace:PdfExample">
<Grid>
<my:FileSystemBrowser HorizontalAlignment="Left" x:Name="fileSystemBrowser1" VerticalAlignment="Top" Height="311" Width="417" RootPath="C:\TFS\AE.Web.ezHealthQuoter.Common\1_Dev\Shared\Pdfs" />
</Grid>
FileSystemBrowser.xaml
<UserControl x:Class="PdfExample.FileSystemBrowser"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
mc:Ignorable="d"
d:DesignHeight="300" d:DesignWidth="300" xmlns:my="clr-namespace:PdfExample">
<DockPanel>
<my:FileSystemTree x:Name="fileSystemTree1" RootPath="{Binding Path=RootPath}" Width="150" />
<ListBox DockPanel.Dock="Right" />
</DockPanel>
FileSystemBrowser.xaml.cs
public partial class FileSystemBrowser : UserControl
{
#region Static Members
static FileSystemBrowser()
{
PropertyChangedCallback rootPathChangedCallback = new PropertyChangedCallback(OnRootPathChanged);
PropertyMetadata metaData = new PropertyMetadata(rootPathChangedCallback);
RootPathProperty = DependencyProperty.Register("RootPath", typeof(string), typeof(FileSystemBrowser), metaData);
}
static DependencyProperty RootPathProperty;
public static void OnRootPathChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
(d as FileSystemBrowser).RootPath = e.NewValue as string;
}
#endregion
public string RootPath
{
get { return this.ViewModel.RootPath; }
set { this.ViewModel.RootPath = value; }
}
public FileSystemBrowserViewModel ViewModel
{
get;
protected set;
}
public FileSystemBrowser()
{
InitializeComponent();
this.ViewModel = new FileSystemBrowserViewModel();
this.DataContext = this.ViewModel;
}
}
public class FileSystemBrowserViewModel : INotifyPropertyChanged
{
private string _rootPath;
public string RootPath
{
get { return _rootPath; }
set { _rootPath = value; RaisePropertyChanged("RootPath"); }
}
#region INotifyPropertyChanged Members
public event PropertyChangedEventHandler PropertyChanged;
protected void RaisePropertyChanged(string propertyName)
{
if (this.PropertyChanged != null)
this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
#endregion
}
FileSystemTree.xaml
<UserControl x:Class="PdfExample.FileSystemTree"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
mc:Ignorable="d"
d:DesignHeight="300" d:DesignWidth="300">
<DockPanel>
<TreeView SelectedValuePath="{Binding Path=SelectedValuePath, Mode=TwoWay}" HorizontalAlignment="Stretch" Name="treeView1" VerticalAlignment="Stretch" ItemsSource="{Binding RootFolder}" HorizontalContentAlignment="Left" VerticalContentAlignment="Top" Margin="0">
<TreeView.ItemTemplate>
<HierarchicalDataTemplate ItemsSource="{Binding Folders}">
<TextBlock Text="{Binding FolderName}" />
</HierarchicalDataTemplate>
</TreeView.ItemTemplate>
</TreeView>
</DockPanel>
FileSystemTree.xaml.cs
public partial class FileSystemTree : UserControl, INotifyPropertyChanged
{
#region Static Members
static DependencyProperty RootPathProperty;
static FileSystemTree()
{
PropertyChangedCallback rootPathChangedCallback = new PropertyChangedCallback(OnRootPathChanged);
PropertyMetadata metaData = new PropertyMetadata(rootPathChangedCallback);
RootPathProperty = DependencyProperty.Register("RootPath", typeof(string), typeof(FileSystemTree), metaData);
}
public static void OnRootPathChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
(d as FileSystemTree).RootPath = e.NewValue as string;
}
#endregion
public string RootPath
{
get { return this.ViewModel.RootPath; }
set { this.ViewModel.RootPath = value; }
}
public FileSystemTreeViewModel ViewModel
{
get;
protected set;
}
public FileSystemTree()
{
InitializeComponent();
this.ViewModel = new FileSystemTreeViewModel();
this.DataContext = this.ViewModel;
}
#region INotifyPropertyChanged Members
public event PropertyChangedEventHandler PropertyChanged;
protected void RaisePropertyChanged(string propertyName)
{
if (this.PropertyChanged != null)
this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
#endregion
}
public class FileSystemTreeViewModel : INotifyPropertyChanged
{
public IFolder[] RootFolder
{
get
{
if (RootPath != null)
return new IFolder[] { new FileSystemFolder(RootPath) };
return null;
}
}
private string _rootPath;
public string RootPath
{
get { return _rootPath; }
set
{
_rootPath = value;
RaisePropertyChanged("RootPath");
RaisePropertyChanged("RootFolder");
}
}
private string _selectedValuePath;
protected string SelectedValuePath
{
get { return _selectedValuePath; }
set { _selectedValuePath = value; }
}
#region INotifyPropertyChanged Members
public event PropertyChangedEventHandler PropertyChanged;
protected void RaisePropertyChanged(string propertyName)
{
if (this.PropertyChanged != null)
this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
#endregion
}
I know that the tree works, because if I just put the tree inside MainWindow.xaml, it's fine. But for some reason, the RootPath value from MainWindow.xaml gets bound into FileSystemBrowser and stops there. It never makes it all the way down to FileSystemTree. What am I missing?
There is to few information to be certain, but I think the problem is the DataContext that is not set. Try relative bindings, this will probably help. In FileSystemBrowser.xaml change the binding as follows:
<my:FileSystemTree x:Name="fileSystemTree1"
RootPath="{Binding Path=RootPath,RelativeSource={RelativeSource Mode=FindAncestor,AncestorType=UserControl}}"
Width="150" />
Another possibility would be to set the UserControls this-reference to the DataContext. This should also help.
How to disable all the properties or some of the properties PropertyChanged event for some time when we are using INotifypropertyChanged?
In order for INotifyPropertyChanged to work, you need to raise the PropertyChanged event. Therefore, to make it not work, you just don't raise that event.
Here's a small example class:
public class NPCExample : INotifyPropertyChanged
{
public NPCExample()
{
}
private string mSomeProperty = "Set Property";
public string SomeProperty
{
get { return mSomeProperty; }
set
{
mSomeProperty = value;
if (mUseNotifyPropertyChanged)
NotifyPropertyChanged("SomeProperty");
}
}
private Boolean mUseNotifyPropertyChanged = true;
public Boolean UseNotifyPropertyChanged
{
get { return mUseNotifyPropertyChanged; }
set
{
mUseNotifyPropertyChanged = value;
NotifyPropertyChanged("UseNotifyPropertyChanged");
}
}
#region INotifyPropertyChanged Members
public event PropertyChangedEventHandler PropertyChanged;
private void NotifyPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
#endregion
}
In this class, each property calls the common "NotifyPropertyChanged" method for raising the PropertyChanged event. There is an additional variable defined (here, I used a public Property so I could bind it to a checkbox) that tells whether or not to raise the event, as used in the SomeProperty event.
Here's a small, quick-n-dirty program to show this in action:
XAML
<Window x:Class="MyNamespace.SelectiveNotifyPropertyChanged"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="SelectiveNotifyPropertyChanged" Height="300" Width="300">
<StackPanel>
<TextBlock Text="{Binding SomeProperty}" />
<CheckBox x:Name="chkINPCEnabled"
Content="Enable INotifyPropertyChanged"
IsChecked="{Binding UseNotifyPropertyChanged}"></CheckBox>
<StackPanel Orientation="Horizontal">
<TextBox x:Name="txtIsProperty"
Text="Set Property" />
<Button x:Name="btnSetProperty"
Content="Set Property" />
</StackPanel>
</StackPanel>
</Window>
Code Behind
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
namespace MyNamespace
{
/// <summary>
/// Interaction logic for SelectiveNotifyPropertyChanged.xaml
/// </summary>
public partial class SelectiveNotifyPropertyChanged : Window
{
public SelectiveNotifyPropertyChanged()
{
InitializeComponent();
NPCExample example = new NPCExample();
this.DataContext = example;
btnSetProperty.Click +=
(s, e) => example.SomeProperty = txtIsProperty.Text;
}
}
public class NPCExample : INotifyPropertyChanged
{
public NPCExample()
{
}
private string mSomeProperty = "Set Property";
public string SomeProperty
{
get { return mSomeProperty; }
set
{
mSomeProperty = value;
if (mUseNotifyPropertyChanged)
NotifyPropertyChanged("SomeProperty");
}
}
private Boolean mUseNotifyPropertyChanged = true;
public Boolean UseNotifyPropertyChanged
{
get { return mUseNotifyPropertyChanged; }
set
{
mUseNotifyPropertyChanged = value;
NotifyPropertyChanged("UseNotifyPropertyChanged");
}
}
#region INotifyPropertyChanged Members
public event PropertyChangedEventHandler PropertyChanged;
private void NotifyPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
#endregion
}
}
If you are referring to a binding, you can set the UpdateSourceTrigger to Explicit, which means any changes won't get saved until you explicitly tell it to update
<TextBox Text="{Binding SomeValue, UpdateSourceTrigger=Explicit}" />
Based on your comment to Rachel it sounds like you might want to set the private property backing member sometimes. Could you expose a public method in your underlying class that would set the private member but not call NotifyPropertyChaged?
Public Class SomeClass
... define property SomeProp and m_SomeProp
Public Sub SetSomeProp(val as string)
m_SomePreop=val
End Sub
End Class