Binding an Element to a Control Property (string) - wpf

so, i've found a way to bind a label to a property on current Control
i give it a name:
<UserControl x:Class="WpfGridtest.GridControl" x:Name="GridControlControl1">
and than bind to property of this control:
<Label Content="{Binding ElementName=GridControlControl1, Path=Filter}"></Label>
I can see the default value i put in that property.
I am guessing that this isn't working because i am binding to String property which doesn't implement INotifyPropertyChanged??
is there some other type i should be using for this property instead of String auto notify my label of changes, or am i going about this the wrong way?

The INotifyPropertyChanged interface should be implemented by the class that contains the property - in this case, by your WpfGridtest.GridControl.
Also, if you want to use your properties for UI, consider using a DependencyProperty as a storage instead of a private field.

in addition, it is also likely that the default binding mode is one time, so you may have to change it in your {Binding}

Related

How to apply Metadata from a ViewModel to the View in WPF with MVVM

I have a viewModel with properties like the following and a set of specific attributes used throughout the viewmodels.
public class MyViewModel : BaseModel
{
[StringLength(50), Required]
[SetLockedForExistingEntities]
public string FirstName { get ... set ... }
public bool IsInNewMode { get; }
}
Now I want to apply such metaData in a view in a consistent way. Like... If bound, set TextBox maxlength from the MaxLengthAttribute. If SetLockedForExistingEntitiesAttribute is set, disable the control in case viewModel is not in some 'New' Mode etc..
Is that doable/a good idea to do with a custom MarkupExtension that replaces "Binding" for VM Bindings? Or would it be better to use a Behavior (applied via attached property) which tries to apply anything it can from the bound ViewModel property to the control it is attached to?
Usage would be like
(A) Attached dependencyproperty that reads the binding from TextBox.Text and applies behaviors
<TextBox Text="{Binding Model.FirstName, ValidatesOnDataErrors=True}" "bb:MyBindingHelper.ApplyViewModelBehaviors="True" />
(B) Custom MarkupExtension that does all in one
<TextBox Text="{BindingWithModelBasedBehaviors Model.FirstName}" />
You could write a markup extension that gets the property from the datacontext and reads attributes.
That would be kind of complicated but you can get the property name of properties where the source changed event was raised.
That looks rather like validation to me.
You could implement inotifydataerrorinfo in a base viewmodel and write code there that validates properties using attributes.
That's how the code in this works:
https://gallery.technet.microsoft.com/scriptcenter/WPF-Entity-Framework-MVVM-78cdc204
That works by the view telling the viewmodel which property's value just passed to the viewmodel.
You can extend the method you use for raising property changed to pass the property name to the validation.
Or you could even do the check from a method called in the property setter before you set the value on a property and not set the value if the new one fails validation.
As a specific property fails validation in a particular way you could run an action.
The production code version of that app I linked also has a dictionary of predicates used as well as attributes. They could have code in them references and sets other viewmodel properties.

WPF - Combobox SelectedItem not getting set?

I have a ComboBox that has its ItemsSource bound to a static List<CustomSettings> of options. The ComboBox is part of a form which is bound to a CustomObject class, and one of the properties on that class is a CustomSettingProperty.
I would like to bind the SelectedItem of the ComboBox to the property specified in the CustomObject, however SelectedItem="{Binding Path=CustomSettingProperty}" is not setting the default selected item. Using breakpoints I can see that it is calling the get; method, so I think the problem might be in the fact the CustomSettingProperty is created separately from the List<CustomObject> so WPF does not think it is the same item.
Is there an easy way to do this? Or perhaps an alternative since the CustomSettings class does contain an Id?
If the item that is selected is not the same instance that is contained in the List, you must override Equals() in the CustomObject to let the ComboBox know that it is the same object.
If it's the same instance, maybe it's only a simple thing such as setting the BindingMode to TwoWay:
SelectedItem="{Binding Path=CustomSettingProperty,Mode=TwoWay}"
I found the solution, It was The Prism's Event Aggregator was passed with reference type so That the ui thread stops processing

Two-way-like binding between a Resource's property and a runtime object property

my problem is the following :
I have defined a TextBox as a child of a ToolBar in a ResourceDictionary (x:Key MyToolbar). When my application loads, it places the ToolBar correctly inside the Window frame, along with its TextBox. So far, so good.
Of course, I'd like that very TextBox to be two-way databound to some objects' properties that are NOT defined in any ResourceDictionary.
More precisely, when the TextBox is all set in the correct window frame, and then, after the “Open” command a certain file is loaded, a Deserializer builds DesignerCanvas object using values from out of that file, in my case it is a string “Token” CLR property of a class that implements INotifyPropertyChanged.
Here some simplified code snippets. I will leave many blanks for clarity’s sake:
Class DesignerCanvas : INotifyPropertyChanged
{
Private string m_token;
Public string Token
{
Get{….
Set{ if (value…)
OnPropertyChanged(“Token”);
}
//notice there is no Constructor other than the default one
}
And on the XAML side I have something like this:
<ToolBar x:Key=”MyToolbar…..
<TextBox …
Now, my two goals are: to have the “static” TextBox resource on my toolbar pick up the values of the DesignerCanvas’ “Token” property as soon as the property changes (i.e. gets a value for the first time, basically), and similarly, and more importantly, I wish to make it possible to have the DesignerCanvas read the values I could put in manually into the TextBox and fill its Token Property with that user-input text (I think I will opt for the TextBox’ LostFocus Event as a trigger for the string value being passed/bound onto the DesignerCanvas’ “Token” Property).
Anyway, I’m not sure how to set up a perfect two-way (or two-way-like) DataBinding between the TextBox' Text property and the DesignerCanvas' Token Property, since we have one static resource (I’m not sure if static is the correct word), and another dynamic runtime object (again not sure if runtime or dynamic are the words).
How do I achieve this? Do I absolutely need to register a “Token”- DependencyProperty in DesignerCanvas? Do I absolutely need to have a XAML for the DesignerCanvas defined somewhere (for example in my Window1.xaml or a dummy s:DesignerCanvas resource along with the TextBox)?
Help appreciated!
Have you tried databinding with your textbox...
<TextBox Text="{Binding Path=Token, Mode=TwoWay}" />
...then when your app loads and places the ToolBar in the window frame, make sure that it also sets the DataContext property of the ToolBar to the instance of your DesignerCanvas class?

How do I link (dependency) properties in my ViewModel?

Simplified example:
I have an object that models a user. Users have a first name and a last name. The UserViewModel has a dependency property for my Models.User object. In the declaration of the UserView's xaml, I want to bind a couple of TextBlocks to the first and last name properties.
What is the correct way to do this? Should I have readonly DependencyProperties for the name fields, and when the dependency property User is set, update them? Can the name fields be regular C# properties instead? Or, should I bind like this:
<TextBlock Text="{Binding User.FirstName}" />
You typically will never use Dependency Properties in your ViewModel or Model classes. You'll want to have your ViewModel implement INotifyPropertyChanged instead.
If you do that, you can bind using the syntax above. (Though, if you want two-way binding to work appropriately, your "User" object will also need to implement INotifyPropertyChanged - otherwise, changes made in code to the user will not automatically reflect in the UI.)

Silverlight databinding question

Let's say I have a Class called ModelBase
public class ModelBase
{
public string Name
{
get { return "one"; }
}
}
and I have a property named Model of type ModelBase.
Now to the question how do I Bind to the Name property? The c# code would be this.Model.Name.
I've been trying to get this to work a long time, can some one enlighten me?
Not sure why you are having trouble with this.
You should be able to set the object that the Model property is on as the DataContext for your control, then simply bind using {Binding Model.Name}...
What have you tried to do so far?
(You can definitely bind to properties in Silverlight BTW)
You need to assign Model to the datacontext property before you can do any data binding, an example would be:
this.DataContext = Model;
In xaml, setup binding in this way:
<TextBlock Text={Binding Name}/>
Note: The way you declare the Name property only allows one time binding, to allow OneWay/TwoWay binding, look at dependencyproperty or INotifyPropertyChanged interface.
You can definitely databind to properties.
If you want more, you can use dependency properties of silverlight.
Check this URL.
Silverlight doesn't allow binding to properties. You'll need to expose a property on your viewmodel that returns the value of the models properties to bind correctly.

Resources