TextBox binding in WPF - wpf

I have a textbox in XAML file, On Changing the text in the textbox the prop setter is not getting called. I am able to get the value in ProjectOfficer textbox and not able to update it. I am using MVVM pattern
Below is my code XAML
TextBox Text="{Binding Path=Officer,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}"
x:Name="ProjectOfficer"/>
ViewModel.cs
public Staff Officer
{
get
{
return __con.PrimaryOfficer ;
}
set
{
_con.PrimaryOfficer = value;
_con.PrimaryOfficer.Update(true);
}
}
Staff.cs
public class Staff : EntityBase
{
public Staff();
public string Address { get; }
public string Code { get; set; }
public override void Update();
}
Thanks

You're binding a property of type string on the TextBox to a property of type Officer on your ViewModel. I expect the setter isn't being called because WPF can't do the conversion.
If you check the output window in visual studio, you'll probably see a binding error for this property.

Try something like:
TextBox text ="{Binding Path=Address,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}"
x:Name="ProjectOfficer"/>
Make sure the holder of the TextBox is linked to a Staff object. The textbox cannot bind directly to an object without telling the property to display (like Address in my example above).

Related

WPF: SelectedItem Binding Not Showing With DisplayMemberPath

I've got a ComboBox (inside a ListView) that used to be tied to a collection of strings. However, I'm switching to having it use a custom class instead.
Now the ComboBox is bound to an ObservableCollection of type Area. For display, I'm showing the Name property with DisplayMemberPath. This works great, but the box is no longer loading with the current value selected.
<ListView x:Name="TestListView" ItemsSource="{Binding TestViewList, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}">
<ListView.View>
<GridView>
<GridViewColumn Header="Area">
<GridViewColumn.CellTemplate>
<DataTemplate>
<ComboBox ItemsSource="{Binding DataContext.AreaList, ElementName=BVTWindow}" DisplayMemberPath="Name" SelectedItem="{Binding Path=Area, UpdateSourceTrigger=PropertyChanged, Mode=TwoWay}" />
public ObservableCollection<ViewTest> TestViewList { get; private set; }
public ObservableCollection<Area> AreaList { get; private set; }
public class ViewTest : BindableBase
{
public string Description { get; set; }
public Area Area { get; set; }
}
public partial class Area
{
public long ID { get; set; }
public string Name { get; set; }
}
"Area" is the same class as the Collection, and is a property of the class the ListView's ItemsSource is bound to. Am I doing this the right way? Any help is much appreciated.
UPDATE:
I had a theory that perhaps using the "Name" property (which is a string) for display in the box made the SelectedItem attribute look for a string rather than something of type Area. I changed the class for TestViewList to use a string to keep track of Area, but that didn't change the program's behavior at all.
UPDATE 2:
Above, I've added the pertinent lines from the view model related to the ComboBox and ListView in question.
Update 3:
I've changed my Area property from inline to expanded, including the SetProperty that handles raising. It now works for new items added to the ItemSource at run-time, but is still a blank selection for on items loaded at program start.
public class ViewTest : BindableBase
{
public string Description { get; set; }
public Area Area
{
get
{
return this.area;
}
set
{
this.SetProperty(ref this.area, value);
}
}
}
Update 4:
It turns out Paul Gibson's answer was correct. The reason my existing entries weren't loading properly had to do with a logic error in the way I was loading items from the database, and not a problem with the xaml bindings. Everything works now (with respect to those ComboBoxes, at least).
Based on what you are saying I think my comment is the answer. This is the case for a single combobox. In your case you need one for every line of the grid, so you may have to programatically add the binding to members of a list by index.
In your view model if you also have (single case):
private Area _curSelArea;
public Area curSelArea
{
get { return _curSelArea; }
set
{
_curSelArea = value;
RaisePropertyChanged("curSelArea");
}
}
Then you can bind to the property with:
SelectedItem="{Binding DataContext.curSelArea . . . }"
The view model can set the initial value of curSelArea if it is known initially.
EDIT: After actually having to do this I found that someone extended the DataGridComboBoxColumn to facilitate better binding. Check out this link if you are trying to do this: http://joemorrison.org/blog/2009/02/17/excedrin-headache-35401281-using-combo-boxes-with-the-wpf-datagrid/

Silverlight: How do i assign a usercontrol's property value to a textbox?

I have a user control which i have added to an outer form in silverlight. The user control has a textbox called txtRoleTitle, i have declared a property in the usercontrol's class called lableName and assigned txtRoleTitle.text to labelName as shown in the code below bellow,
in the silverlight property panel, under the miscellaneous menu, i have set labelName to "Landlord", then added another one of this user control to the outerform and set its labelName to Tenant. But this does not seem to work when i run the silverlight dialogue. The value of the labelName does not appear in the textbox during design and run time.
Here is my code below. thanks
public partial class UserRoleDetails : UserControl
{
public string labelName { get; set; }
public UserRoleDetails()
{
InitializeComponent();
this.txtRoleTitle.Text = labelName;
}
}
You are setting the value of txtRoleTitle.Text in your constructor, at the point of the assignment the labelName property will not have a value.
I think you need to look at making your labelName a dependency property and binding your txtRoleTitle control in the user control's xaml. Take a look at this example : http://stevenhollidge.blogspot.co.uk/2012/03/dependency-properties-in-user-control.html
First of all, your class should implement INotifyPropertyChanged interface
Secondly, you should make labelName property as notify property.
Thirdly, you should bind text property of txtRoleTitle to your notify property.
Alright, you are done.
Sample: http://social.msdn.microsoft.com/Forums/en-US/silverlightcontrols/thread/052a2b67-20fc-4f6a-84db-07c85ceb3303/
I had a look at dependancy property solution. Although while this may work if implemented properly, for what i am trying to do, this is an overkill solution. So i have a simple solution that works now, see code below:
public partial class UserRoleDetails : UserControl
{
public string labelName
{
get {return this.txtRoleTitle.Text;}
set {this.txtRoleTitle.Text = value;}
}
public UserRoleDetails()
{
InitializeComponent();
}
}

TextBlock binding not working

I have a TextBlock that bind to property in my model. My model sitting in my view model that bind with the window.
<TextBlock Text="{Binding MyModel.TextVar,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}"></TextBlock>
TextVar is a string property that call function of Notify...
So, I do not understand why it does not work. (There is no binding error in the OutPut).
EDIT:
string _textVar;
public string TextVar
{
get
{
return _textVar;
}
set
{
_textVar= value;
NotifyPropertyChanged("TextVar");
}
}
private void NotifyPropertyChanged(string propertyName)
{
if (PropertyChanged != null)-- HERE THE PROPBLEM, IT ARRIVE NULL
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
public event PropertyChangedEventHandler PropertyChanged;
Seems that everything is perfect, now just add this line under the constructor of your class.
this.DataContext = this;
The problem arries when you have declared another DataContext in some parent window. I was suffering from same problem and this solution worked for me.
A Quick Review of Binding a TextBox in WPF
Step 1: Declare a property in class of window
first of all, you should declare a property in class of you window, i.e in .xml.cs file of your new window.
string _someVariable;
public string NameOfProperty
{
get
{
return _someVariable;
}
set
{
_someVariable= value;
}
}
Step 2: Bind the property to TextBox
Now bind your TextBox to your newly created property using the following syntax.
{Binding Path=NameOfProperty}
The Path notes the property that you want to bind to, however, since Path is the default property of a binding, you may leave it out if you want to, like this:
{Binding NameOfProperty}
Step 3: Declare the DataContext of your Window
Your solution should work until now, but in case you are using some pattern you should define the DataContext of your window.
Binding TextBlock with Mode=TwoWay makes no sense because its a TextBlock and not a TextBox.
but nevertheless your binding work if the DataContext of your textblock has a Property "MyModel" and this "MyModel" - object has a Property "TextVar".
if you wanna look up your datacontext and binding at runtime use Snoop
EDIT: that what you need if you do your binding like you did
public class MyViewmodel
{
public MyOtherClass MyModel {get;set;}
}
public class MyOtherClass
{
public string TextVar {get;set;}
}
windows.xaml.cs ctor:
this.data = new MyViewmodel();
this.DataContext = this.data;

Updating a dependency property based on changes in the view model

I'm having some problems with data binding in WPF. Here's the scenario: I have made a user control which simulates a Dial Pad (i.e., an array of 12 buttons with the digits from '0' to '9' plus the '#' and 'Clear' keys). The control lives inside a class library and it's been implemented following the MVVM pattern, mainly because I need the components in the class library to be easily unit tested.
The view model for the control is quite simple, it basically updates a public "DialedNumber" string (which is internally connected to the model) every time the user presses a dial pad key button. The binding is working correctly and, by using the debugger, I can confirm that the "DialedNumber" variable inside the viewmodel is getting updated as I press button in the dial pad.
This DialPad control is used by a separate XAML file (Panel.xaml), which laids out several controls that belong to my custom class library.
Now, I'd like to add a TextBlock inside my Panel file in order to display the "DialedNumber" string held inside the DialPad. This is the code snippet in Panel.xaml:
<PanelControls:DialPad x:Name="MyDialPad" DialedNumber="55325"/>
<TextBlock Text="{Binding ElementName=MyDialPad, Path=DialedNumber}" />
The result I'm getting is that the textblock displays the correct number on start (i.e., "55325"), but its content doesn't get updated as I press the dial pad keys (even though the DialPad's viewmodel gets updated as I press new keys, as I've checked with the debugger).
Here's the code behind for the DialPad view:
public partial class DialPad : UserControl
{
public DialPad()
{
InitializeComponent();
DataContext = new DialPadViewModel();
}
public void DialedNumberChanged(object sender, EventArgs e)
{
return;
}
public DialPadViewModel DialPadViewModel
{
get { return DataContext as DialPadViewModel; }
}
public string DialedNumber
{
get
{
var dialPadViewModel = Resources["DialPadVM"] as DialPadViewModel;
return (dialPadViewModel != null) ? dialPadViewModel.DialedNumber : "";
}
set
{
var dialPadViewModel = Resources["DialPadVM"] as DialPadViewModel;
if (dialPadViewModel != null)
{
dialPadViewModel.DialedNumber = value;
}
}
}
}
Here's the DialPad view model:
public class DialPadViewModel : ObservableObject
{
public DialPadViewModel()
{
_dialPadModel = new DialPadModel();
}
#region Fields
private readonly DialPadModel _dialPadModel;
private ICommand _dialPadKeyPressed;
#endregion
#region Public Properties/Command
public DialPadModel DialPadModel
{
get { return _dialPadModel; }
}
public ICommand DialPadKeyPressedCommand
{
get
{
if (_dialPadKeyPressed == null)
{
_dialPadKeyPressed = new RelayCommand(DialPadKeyPressedCmd);
}
return _dialPadKeyPressed;
}
}
public string DialedNumber
{
get { return _dialPadModel.DialedNumber; }
set
{
_dialPadModel.DialedNumber = value;
RaisePropertyChanged("DialedNumber");
}
}
#endregion
#region Private Helpers
private void DialPadKeyPressedCmd(object parameter)
{
string keyPressedString = parameter.ToString();
if (keyPressedString.Length > 0)
{
if (char.IsDigit(keyPressedString[0]))
{
DialedNumber += keyPressedString[0].ToString(CultureInfo.InvariantCulture);
}
else if (keyPressedString == "C" || keyPressedString == "Clr" || keyPressedString == "Clear")
{
DialedNumber = "";
}
}
}
#endregion
}
Let me restate my problem: the textblock in Panel.xaml displays the correct number (55325) on start, but its value never gets updated as I press the DialPadButtons. I've placed a breakpoint inside DialPadKeyPressedCmd and I can confirm that the method gets executed everytime I press a key in the dial pad.
DependencyProperties are meant to point to some other property to get their value. So you can either point it to your DialPadViewModel.DialedNumber, or you can point it to some other string when the UserControl is used (either a binding or a hardcoded value like "551"), but you can't do both.
In your case, when someone binds to the DialedNumber dependency property, they are replacing the current value (the binding to DialPadViewModel.DialedNumber) with a new value.
Depending on how your code looks and what you want to do, there are a few ways around it.
First, you could insist that people who want to use your control also use your ViewModel, and don't make DialedNumber a public dependency property.
So instead of being allowed to create a custom class with a property of SomeOtherDialedNumber and binding
<DialPad DialedNumber="{Binding SomeOtherDialedNumber}">
they are forced to use the DialPadViewModel in their code anytime they want to use the DialPad control. For this to work, you would need to remove the this.DataContext = new DialPadViewModel in your code-behind the UserControl since the user will be providing the DialPadViewModel to your UserControl, and you can use an implicit DataTemplate to tell WPF to always draw DialPadViewModel with your DialPad UserControl.
<DataTemplate DataType="{x:Type DialPadViewModel}">
<local:DialPad />
</DataTemplate>
The other alternative I can think of is to synchronize your DependencyProperty with your ViewModel property with some PropertyChange notifications.
You would need to update DialPadViewModel.DialedNumber anytime the DialedNumber dependency property changes (You may need to use DependencyPropertyDescriptor.AddValueChanged for property change notification), and you would also have to write something to update the source of the DialedNumber dependency property anytime DialPadViewModel.DialedNumber changes.
Personally, if my UserControl has a ViewModel then I use the first option. If not, I get rid of the ViewModel entirely and build the logic for my UserControl in the code-behind, without a ViewModel.
The reason for this is that WPF works with two layers: a UI layer and a data layer. The DataContext is the data layer, and a ViewModel is typically part of the data layer. By setting the data layer (DataContext) explicitly in the UserControl's constructor, you are combining your data layer with your UI layer, which goes against one of the biggest reasons for using MVVM: separation of concerns. A UserControl should really just be a pretty shell only, and you should be able to place it on top of any data layer you want.
If you place your DialPad in your View, you can create a DialPadViewModel-Property (public+global) in your ViewViewModel:
public DialPadViewModel DialPadViewModel = new DialPadViewModel();
Now set the DataContext-Binding of your View to the ViewViewModel and bind the DialPads DataContext also to it, like
<local:DialPad DataContext="{Binding}"/>
Now you can bind to the properties in your DialPadViewModel:
<TextBox Text="{Binding Path=DialPadViewModel.DialedNumber}"/>
Thats how you can Access your DialPadViewModel from your View and your DialPad.
EDIT:
Now try changing your DialedNumber Property in your DialPad.xaml.cs like this:
public string DialedNumber
{
get
{
return DialPadViewModel.DialedNumber;
}
set
{
DialPadViewModel.DialedNumber = value;
}
}
EDIT 2: I found the Problem:
In your DialPad.xaml all your Commands were bound to the DialPadViewModel from the resources, while the TextBloc was bound to the DialPads DataContext, which is another instance of the DialPadViewModel.
So everytime you hit a DialPad-Button you changed the value of the DialedNumber from the resources' DPVM-instance not the DialedNumber from the DataContext's DPVM-instance.
It sounds like you can add a TextBox to your view and bind it's Text property to your view-model's DialedNumber property.
<TextBox Text="{Binding Path=DialedNumber}"></TextBox>
Your view-model property can look something like this:
private string _dialedNumber;
[DefaultValue("551")]
public string DialedNumber
{
get { return _dialedNumber; }
set
{
if (value == _dialedNumber)
return;
_dialedNumber= value;
_yourModel.DialedNumber= _dialedNumber;
this.RaisePropertyChanged("DialedNumber");
}
}
Let me know if I misunderstood your question.

Can I use XAML to set a nested property (property of the value of a property) of a control?

I've got a WPF Control that exposes one of it's children (from it's ControlTemplate) through a read-only property. At the moment it's just a CLR property, but I don't think that makes any difference.
I want to be able to set one of the properties on the child control from the XAML where I'm instantiating the main control. (Actually, I would like to bind to it, but I think setting it would be a good first step.)
Here's some code:
public class ChartControl : Control
{
public IAxis XAxis { get; private set; }
public override void OnApplyTemplate()
{
base.OnApplyTemplate();
this.XAxis = GetTemplateChild("PART_XAxis") as IAxis;
}
}
public interface IAxis
{
// This is the property I want to set
double Maximum { get; set; }
}
public class Axis : FrameworkElement, IAxis
{
public static readonly DependencyProperty MaximumProperty = DependencyProperty.Register("Maximum", typeof(double), typeof(Axis), new FrameworkPropertyMetadata(20.0, FrameworkPropertyMetadataOptions.AffectsRender, OnAxisPropertyChanged));
public double Maximum
{
get { return (double)GetValue(MaximumProperty); }
set { SetValue(MaximumProperty, value); }
}
}
Here's the two ways I can think of setting the nested property in XAML (neither compile):
<!--
This doesn't work:
"The property 'XAxis.Maximum' does not exist in XML namespace 'http://schemas.microsoft.com/winfx/2006/xaml/presentation'."
"The attachable property 'Maximum' was not found in type 'XAxis'."
-->
<local:ChartControl XAxis.Maximum="{Binding Maximum}"/>
<!--
This doesn't work:
"Cannot set properties on property elements."
-->
<local:ChartControl>
<local:ChartControl.XAxis Maximum="{Binding Maximum}"/>
</local:ChartControl>
Is this even possible?
Without it I guess I'll just need to expose DP's on the main control that get bound through to the children (in the template). Not so bad, I guess, but I was just trying to avoid an explosion of properties on the main control.
Cheers.
You can't do it like this... you can access nested properties through its path in a binding, but not when you define the value of the property.
You have to do something like that :
<local:ChartControl>
<local:ChartControl.XAxis>
<local:Axis Maximum="{Binding Maximum}"/>
</local:ChartControl.XAxis>
</local:ChartControl>

Resources