Binding label to a variable - c#

I am just starting with WPF and I am trying to setup binding between a local variable and a label. Basicaly I want to update the label when local variable changes. I was searching for solution but they all just use textbox as a source not just class variable and I am not even sure it works this way. So here is my code.
public partial class MainWindow : Window
{
int idCounter;
public MainWindow()
{
InitializeComponent();
Binding b = new Binding();
b.Source = idCounter;
b.Mode = BindingMode.OneWay;
b.UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged;
myLabel.SetBinding(Label.ContentProperty,b);
}
private void Button_Click(object sender, RoutedEventArgs e)
{
idCounter++;
}
}
Button does work, idCounter changes value, but it does not update in label so I guess binding is wrong. Can someone tell me what is wrong? Thanks

Your code will work if you change your class to this...
public partial class Window1 : Window, INotifyPropertyChanged
{
private int _idCounter;
public int IdCounter
{
get { return _idCounter; }
set
{
if (value != _idCounter)
{
_idCounter = value;
OnPropertyChanged("IdCounter");
}
}
}
public Window1()
{
InitializeComponent();
myLabel.SetBinding(ContentProperty, new Binding("IdCounter"));
DataContext = this;
}
private void Button_Click(object sender, RoutedEventArgs e)
{
e.Handled = true;
IdCounter++;
}
#region INotifyPropertyChanged Implementation
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged(string name)
{
var handler = System.Threading.Interlocked.CompareExchange(ref PropertyChanged, null, null);
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(name));
}
}
#endregion
}
Some of the issues you were having are...
The window itself should implement INotifyPropertyChanged so that the binding engine can place an ear on it.
the IdCounter needs to be public and have a public getter on it so that the binding engine can 'get' it.
You should set the DataContext to whatever class has declared IdCounter (the MainWindow in this case). Part of the problem was that the binding engine had no DataContext.
The BindingMode setting was a red-herring since a Label binds that way by default.
The UpdateSourceTrigger was a red-herring since the content of the label does not have a mechanism to update the source property. A label's content is not like a text box where the user can type something that the code needs to know about. When you're binding to something that the user cannot change, forget about UpdateSourceTrigger, it's the Target property that counts.
The handler should mark the event. This is good practice and did not affect the binding.
The binding constructor needs only the path.
This code will give you your expected result; i.e., that the label updates when the button is clicked. Checked, compiled, and executed on vs2013, .net 4.5.
The other respondents said you should use a View Model. I agree with this 100%, and overall it's a good thing to consider.

You want to use a property to do this, as well as implementing INotifyPropertyChanged so that the label's content gets updated when the property changes.
Here's an example using a simple ViewModel
xaml:
<Window x:Class="WpfApplication1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:converters="clr-namespace:WpfApplication1"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<StackPanel>
<Label Width="200" Height="50" Content="{Binding MyLabel}"/>
<Button Height="30" Width="100" Content="Increment" Click="Button_Click" />
</StackPanel>
</Window>
xaml.cs:
namespace WpfApplication1
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
MainViewModel vm = new MainViewModel();
public MainWindow()
{
InitializeComponent();
this.DataContext = vm;
}
private void Button_Click(object sender, RoutedEventArgs e)
{
vm.MyLabel += 1;
}
}
}
MainViewModel.cs:
namespace WpfApplication1
{
public class MainViewModel : INotifyPropertyChanged
{
#region Members
private int _myLabel;
#endregion Members
#region Properties
public int MyLabel
{
get
{
return _myLabel;
}
set
{
_myLabel = value;
NotifyPropertyChanged("MyLabel");
}
}
#endregion Properties
public MainViewModel()
{
}
#region INotifyPropertyChanged
public event PropertyChangedEventHandler PropertyChanged;
private void NotifyPropertyChanged(String propertyName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
#endregion
}
}
Note: Ideally, you would want to use a Command for the Button instead of a Click event handler

You cannot bind to something that is private or a field so convert it into public property. You can find more as to what is a valid binding source here
If you want changes to your property be picked up by UI you should implement INotifyPropertyChanged interface and raise event each time value of the property changes. So idCounter should look more like this:
private int _idCounter;
public int idCounter
{
get { return _idCounter; }
set
{
if (_idCounter != value)
{
_idCounter = value;
OnPropertyChanged("idCounter");
}
}
}
When you create binding to property you use Path
Binding works in binding context so you need to specify from where to take this Path. Easiest way to do that is to set DataContext. So in your case initialization should look more like this:
Binding b = new Binding("idCounter");
b.Mode = BindingMode.OneWay;
b.UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged;
myLabel.SetBinding(Label.ContentProperty, b);
DataContext = this;
As #d.moncada suggested in his answer you should create dedicated view model

Related

How to save WPF textbox value to variable

Im trying to make a WPF based program that will read the textbox input (user input) from a usercontrol and save it as a object proprety. The usercontrol is added to MainWindow. From MainWindow, you have a button which displays a message box with the textbox value. I'm not sure how to connect it all.
Error = CS0103 The name 'minJpValue' does not exist in the current
context WpfApp1
Please help
(Usercontrol .xaml code)
<TextBox x:Name="minJpValue"/>
(Custom class)
public class jpData
{
public double minJpValue
{
get { return minJpValue; }
set { minJpValue = value; }
}
}
(MainWindow .cs code)
private void clickclick(object sender, RoutedEventArgs e)
{
MessageBox.Show(minJpValue);
}
The issue can be easily fixed using the MVVM Patterns,
The code for the usercontrol will be similar to this
<Grid Background="Red">
<TextBox x:Name="minJpValue" Text="{Binding Path=minJpValue}" />
</Grid>
Create new ViewModel for the MainWindow as follows
public class MainWindowViewModel : INotifyPropertyChanged
{
/// <summary>
/// Property Changed Event Handler
/// </summary>
public event PropertyChangedEventHandler PropertyChanged;
// Create the OnPropertyChanged method to raise the event
protected void OnPropertyChanged(string name)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(name));
}
}
private String _minJpValue;
public String minJpValue {
get { return _minJpValue; }
set {
_minJpValue = value;
OnPropertyChanged(nameof(minJpValue));
}
}
}
Add the usercontrol into your MainWindow view and in the codebehind set the datacontext to the ViewModel as follows
public MainWindowViewModel CurrentModel = new MainWindowViewModel();
public MainWindow()
{
InitializeComponent();
this.DataContext = CurrentModel;
}
private void Button_Click(object sender, RoutedEventArgs e)
{
MessageBox.Show(CurrentModel.minJpValue);
}
This can solve your current problem. Please see that its working as per expected.
For this quick fix use:
MessageBox.Show(minJpValue.Text);
But a better way would be to store the value on a VM (View Model) and bind the control to it using the MVVM pattern. I provide a basic example on
Xaml: ViewModel Main Page Instantiation and Loading Strategy for Easier Binding
Ok let's Understand wt have u done wrong.
<TextBox Name="minJpValue"/>
This line of will Create an object for TextBox and the object will be referred with ur name
minJpValue as u mentioned this will be inside another Usercontrol object and u r try to minJpValue in MainWindow how does it even know that something like minJpValue this exists
So Here is the answer:
objjpData.minJpValue = minJpValue.Text;//Inside user control when ever u change the `minJpValue` u need to set it too bjjpData.minJpValue
pass this objjpData to mainwindow or where u wanna acesses then
MessageBox.Show(objjpData.minJpValue);
Option 2:
MessageBox.Show(UserControlObject.minJpValue.Text);
And PS: Check MVVM once

Disable ComboBox of a UserControl from another UserControl without MVVM

I have a UserControl Person_UC and Student_UC. There is a ComboBox in Student_UC which I want to disable it from Person_UC.
But its not working. I want to accomplish this without MVVM.
public partial class Person_UC : UserControl
{
public Person_UC()
{
InitializeComponent();
Student_UC su = new Student_UC();
su.myComboBoxName.IsEnabled = false;
}
}
Without MVVM it would be quite hard to solve. You have to manipulate the same instance of Student_UC which is currently used.
Actually, you're instantiating a new Student_UC and disabling its ComboBox, but you're not doing anything with your variable "su". Did you assign it somewhere?
Basically, you should have one ViewModel per UserControl, so a ViewModel for Person_UC and a ViewModel for Student_UC.
Warning, this solution requires you to use a MVVM Framework like MVVM Light (https://mvvmlight.codeplex.com) for sending messages.
One standard way would be sending a message. Bind your Loaded event of your Person_UC to a method in your code-behind like so:
<UserControl x:Class="YourAssembly.Person_UC"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Name="Person_UC"
Loaded="Loaded">
<Grid Name="RootGrid">
</Grid>
</UserControl>
And:
public partial class Person_UC : UserControl
{
public Person_UC()
{
InitializeComponent();
}
private void Loaded(object sender, RoutedEventArgs e)
{
//Use a Message to notify your Student_UC's ViewModel that you would like to disable its ComboBox
Messenger.Default.Send<ChangeComboBoxEnabilityMessage>(new ChangeComboBoxEnabilityMessage(false));
}
}
Then, when you receive the message within the Student_UC's ViewModel, you have to pass this information to the view. Basically, you can bind IsEnable property of the ComboBox to a property in its ViewModel, that you will set to false when the message is received.
public class Student_UC_ViewModel : INotifyPropertyChanged
{
public Student_UC_ViewModel()
{
//Register your message
Messenger.Default.Register<ChangeComboBoxEnabilityMessage>(message => ComboBoxIsEnabled = message.ComboBoxIsEnabled);
}
private bool _comboBoxIsEnabled;
public bool ComboBoxIsEnabled
{
get
{
return _comboBoxIsEnabled;
}
set
{
_comboBoxIsEnabled = value;
OnPropertyChanged("ComboBoxIsEnabled");
}
}
public event PropertyChangedEventHandler PropertyChanged;
protected void OnPropertyChanged(string name)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(name));
}
}
}
And your message class:
public class ChangeComboBoxEnabilityMessage : MessageBase
{
public ChangeComboBoxEnabilityMessage(bool comboBoxEnabled)
{
ComboBoxIsEnabled = comboBoxEnabled;
}
public bool ComboBoxIsEnabled
{
get;
set;
}
}
I let you bind your IsEnable property of your ComboBox in your Student_UC xaml to the property of its ViewModel (i.e ComboBoxIsEnabled).
Don't forget to make sure your DataContext is set:
public partial class Student_UC : UserControl
{
public Person_UC()
{
InitializeComponent();
DataContext = new Student_UC_ViewModel();
}
...
}
Also, take care of your binding issues, see your output console in Visual Studio.

INotifyPropertyChanged in nested object

I have 2 main classes. The first class represents a Cell that can have values X, O or Empty. I have implemented INotifyPropertyChanged on this.
public class Cell : INotifyPropertyChanged
{
private Symbol state;
public Symbol State
{
get { return state; }
set
{
if (value == Symbol.X || value == Symbol.O)
state = value;
OnPropertyChanged("State");
}
}
public Cell()
{
state = Symbol.Empty;
}
public enum Symbol
{
X, O, Empty
}
public event PropertyChangedEventHandler PropertyChanged;
private void OnPropertyChanged(string propName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propName));
}
}
}
The second class contains an object of this class and is also set as the datacontext for my main window.
public class Board
{
private Cell testCell;
public Cell TestCell
{
get { return testCell; }
set { testCell = value; }
}
public Board()
{
TestCell = new Cell();
}
public void Cell_Click(int cellNum)
{
TestCell.State = Cell.Symbol.O;
}
}
In my mainwindow I have set the datacontext as board, and also contains a button_click function.
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
this.DataContext = new Board();
}
private void Button_Click(object sender, RoutedEventArgs e)
{
Board board = this.DataContext as Board;
board.Cell_Click(cellNum);
}
}
In my XAML I have bound to Cell object within board using a button style like this:
<Setter Property="Background" Value="{Binding TestCell,
Converter={StaticResource BGConverter}}"/>
BGConverter is a custom converter that accepts a Cell object and converts it into a Colors object. I believe I am indeed directly binding to an object that has INotify implemented, so there's no issue of nested objects. However the binding doesn't reflect changes when I click. When debugging, I found that PropertyChanged event is always null.
The closest answer I found for this is that the event will be subscribed to only if the class Cell is my datacontext. Atleast that's what I understood. How can I correct this problem?
Also I am fresh out of college, currently learning WPF on a new job, so any general recommendations are welcome too.
Thanks
Simply bind to TestCell.State instead of TestCell
I'm pretty new at this myself, but I believe your data context needs to implement INotifyPropertyChanged as well.
That is, your Board class needs to listen to the PropertyChanged event of the cells and fire its own PropertyChanged event when this happens.

Changing wpf elements/controls from another class or static method in c#

I have a MainWindow that contains a text-block [statusTextblock] which has binding to a string [StatusText]. StatusTextblock needs to display combobox results from another window. I pass this data back to mainwindow when it changes in the other window and I've made a static method to change the string when this happens.
However, the staticness of all this leaves me unable to change my textbox element at any point to the new value of StatusText.
I thought about work arounds to bring the changes about when the user returned to Mainwindow but I've not succeeded. I tried the activate and uielement gotfocus event handler (i feel the 2nd one is still a possible fix).
Mainwindow also happens to be always open if that matters. I also prefer doing things in code than xaml, but would be grateful for any help.
Any ideas?
MainWindow xaml, then program entry method, then static event to change statusText
<TextBlock Margin="190,0,0,0" HorizontalAlignment="Right" Name="StatusTextBlock" Text= {Binding}" ></TextBlock>
public MainWindow() //Obviously more went here, but it's not relevent
{
StatusTextBlock.DataContext = statusText;
}
static public void changeStatusText(string status)
{
statusText = status;
}
The problem becomes simpler to solve when you try to implement the application using MVVM pattern.
Define a view model class which has a string property StatusText:
public class MainViewModel : INotifyPropertyChanged
{
private string _statusText;
public event PropertyChangedEventHandler PropertyChanged;
public string StatusText
{
get
{
return _statusText;
}
set
{
if (value == _statusText)
return;
_statusText = value;
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs("StatusText"));
}
}
}
Set the DataContext of the MainWindow to an instance of the MainViewModel:
public MainWindow //Obviously more went here, but it's not relevant
{
private static MainViewModel _mainViewModel = new MainViewModel();
public MainWindow()
{
this.DataContext = _mainViewModel;
}
static public void ChangeStatusText(string status)
{
_mainViewModel.StatusText = status;
}
}
Set the data binding to the view model:
<TextBlock Margin="190,0,0,0" HorizontalAlignment="Right" Name="StatusTextBlock" Text="{Binding StatusText}" ></TextBlock>

Data binding in WPF on button click

I am trying to implement data binding, and to have TextBox's text to be update once I click on some button.
XAML:
<TextBox Text="{Binding Path=Output}" />
Code:
public MainWindow()
{
InitializeComponent();
DataContext = Search;
Search.Output = "111";
}
public SearchClass Search = new SearchClass();
private void button1_Click(object sender, RoutedEventArgs e)
{
Search.Output = "222";
}
public class SearchClass
{
string _output;
public string Output
{
get { return _output; }
set { _output = value; }
}
}
When I execute the program, I see "111", so the binding from MainWindow() works, but if I click a button - the text in the TextBox is not updated (but in the debugger I see that button1_Click is executed and Search.Output is now equal to "222"). What am I doing wrong?
You should implement INotifyPropertyChanged in your SearchClass and then in setter raise the event:
public event PropertyChangedEventHandler PropertyChanged = delegate { };
public string Output
{
get { return _output; }
set
{
_output = value;
PropertyChanged(this, new PropertyChangedEventArgs("Output"));
}
}
If I understood right, SearchClass is the DataContext for your TextBlock. In this case implementing as above would help.
When WPF see some class as the source of Binding - it tries to cast it to INotifyPropertyChanged and subscribe to PropertyChanged event. And when event is raised - WPF updates the binding associated with sender (first argument of PropertyChanged). It is the main mechanism that makes binding work so smoothly.
You have to implement the INotifyPropertyChanged interface on your SearchClass class. This is how binder values are notified their source values have changed. It displays the "111" value because it hasn't been laid out yet (more or less), but will won't update after that until you implement that interface.

Categories

Resources