App.cs
class customRadioButton:RadioButton
{
private Brush enableColor;
private Brush disableColor;
public EnableColor()
{
get{ /*get value */}
set{ /* set value */}
}
}
Main.xaml
<local:customRadioButton EnableColor={Binding ElementName=disableButton, Path=EnableColor} />
<local:customRadioButton x:Name="disableButton" EnableColor="Red", Path=EnableColor} />
Now I am changing the value of EnableColor dynamically. Problem I am having is that the value assigned but is not getting reflected in main.window
I don't want to use dependency property
Is there any other method to Tell the Binded Elements that its property has changed.
Note:I have tried UpdateTrigger its also not working
In order to get Binding work, you will need to create a DependencyProperty.
public Brush EnableColor
{
get { return (Brush)this.GetValue(EnableColorProperty); }
set { this.SetValue(EnableColorProperty, value); }
}
public static readonly DependencyProperty EnableColorProperty = DependencyProperty.Register(
"EnableColor", typeof(Brush), typeof(customRadioButton), new PropertyMetadata(default(Brush));
Read MSDN for details.
Curious what your aversion is to using a dependencyproperty? I answering this on my phone so cant mock one up for you but it would be extremely simple to do.
Just do a Google for "WPF custom control dependency property example" and do exactly what they do just customized for your needs.
The dependency peppery will give you the change notification that you're looking for.
The UpdateTrigger would only apply if you were binding to something that's part of your XAML data context. I mean I guess toy could fudge around to get that to work but DependencyProperty is absolutely the way too go
Related
I read this post and this one about depency properties and I am confused, are all properties in XAML dependency properties ? and what about normal properties we define in C# ? I mean like this : Public int num {get; set;} .
Because the normal properties in C# have some features that they mentioned as a option for dependency property for example I can bind their values to a textbox value.
And if you can make a simple example I will be grateful.
I feel that the other posts answer what a Dependency Property is fairly well so I will address your question showing how to make a Dependency Property, hopefully that will help.
Are all properties in XAML dependency properties?
No, Dependency properties must be specified as such. See below...
public class MyDataGridControl : DataGrid
{
public string SomeName
{
get { return (string)GetValue(SomeNameProperty); }
set { SetValue(SomeNameProperty, value); }
}
public static readonly DependencyProperty SomeNameProperty =
DependencyProperty.Register(
nameof(SomeName), typeof(string), typeof(MyDataGridControl),
new PropertyMetadata(null));
}
In the example above, I have created a class that inherits from DataGrid to make my own DataGrid control. I have created the "normal property" SomeName. I then register SomeName as a Dependency Property. Notice that while SomeName is a "normal property", the getter and setter are referencing the SomeNameProperty Dependency Property.
In my WPF Project, i am trying to create an ObservalbeCollection dependency property inside a custom control. I am not sure if i am doing it the right way but i am using the below code :
public static readonly DependencyProperty MenuOptionsDependency = DependencyProperty.Register("MenuOptions", typeof(ObservableCollection<TextBlock>), typeof(DropDownButton));
public ObservableCollection<TextBlock> MenuOptions
{
get
{
return (ObservableCollection<TextBlock>)GetValue(MenuOptionsDependency);
}
set
{
SetValue(MenuOptionsDependency, value);
}
}
The problem arises when i try to add TextBlocks through XAML to this control as follows :
<local:CustomControl1 x:Name="cmm">
<local:CustomControl1.MenuOptions>
<TextBlock/>
</local:CustomControl1.MenuOptions>
</local:CustomControl1>
This throws a design time error saying :
Collection 'CustomControl1'.'MenuOptions' is null
After going through the accepted answer on this SO post, i understand ObservableCollection, being a reference type, will be null as it will be default value. I read through the answer but i am still unclear/unsure on how to implement the solution in my situation.
I need to be able to add objects to the collection through XAML(and also through C#). I would really appreciate if someone points out where i am missing/what i am doing wrong.
You must never set the default value of a collection type dependency property to something else than null. When you assign a non-null default value by (static) property metadata, all instances of your control will use the same collection object.
Instead, set a default value in the control's constructor by SetCurrentValue:
public DropDownButton()
{
SetCurrentValue(MenuOptionsDependency, new ObservableCollection<TextBlock>());
}
Besides that, there is a strict naming convention, according to which the dependency property identifier field must be named as the property with a Property suffix. So your MenuOptionsDependency should actually be named MenuOptionsProperty.
It's also unclear whether the property type really needs to be ObservableCollection. You don't seem to register a CollectionChanged event handler anywhere, which indicates that your control is not supposed to react on such changes.
Consider a property declaration like this:
public DropDownButton()
{
SetCurrentValue(MenuOptionsProperty, new List<TextBlock>());
}
public static readonly DependencyProperty MenuOptionsProperty =
DependencyProperty.Register(
nameof(MenuOptions), typeof(IEnumerable<TextBlock>), typeof(DropDownButton));
public IEnumerable<TextBlock> MenuOptions
{
get { return (IEnumerable<TextBlock>)GetValue(MenuOptionsProperty); }
set { SetValue(MenuOptionsProperty, value); }
}
I'm puzzled by this probably trivial matter. I have my custom property on a descendant of DevExpresses class LayoutGroup (shouldn't make any difference IMO):
public class ExpandableLayoutGroup : LayoutGroup
{
public static readonly DependencyProperty IsExpandedProperty = DependencyProperty.Register("IsExpanded", typeof(Boolean), typeof(ExpandableLayoutGroup));
public Boolean IsExpanded
{
get { return (Boolean) GetValue(IsExpandedProperty); }
set
{
expandCheckBox.IsChecked = value;
SetValue(IsExpandedProperty, value);
}
}
}
Then I have XAML binding to a listbox (containing 2 items at this time) called listStates.
<ExpandableLayoutGroup x:Name="groupTool" IsExpanded="{Binding SelectedValue.IsTool, ElementName=listStates}" DataContext="{Binding Tool}" Header="Tool" View="GroupBox" />
The object list binding to listStates contains both properties (simplified):
public class State
{
public Boolean IsItemTool { get; private set; }
public Tool Tool { get; private set; }
}
Am I missing something obvious? Because I would expect that when I change listbox selection (single) it would also update IsExpanded property on a group. I have more subproperties of Tool binded (as apparent by DataContext="{Binding Tool}") and those update well. So the DataContext is changing correctly on listbox selection. Except this one property IsExpanded (that should expand/collapse layoutgroup).
What am I doing wrong, and how to make it so, that when listbox changes, IsExpanded binding is polled to get value from IsTool, and will set it (depending on selection).
Getters and setters of dependency properties must contain only GetValue and SetValue calls, because there're two ways to get and set their values: using getters and setters and using DependencyProperty or DependencyPropertyKey. This is why code in your setter is not executed (bindings don't use them for dependency properties). If you want some code to be executed when the value is changed, specify it as a PropertyChangedCallback callback in PropertyMetadata.
See PropertyChangedCallback Delegate on MSDN.
The setter for a dependency property must only set the value for it's underlying type. The .NET internals reserve the right to call SetValue() directly (and in my experience WPF usually does, while Silverlight uses the setter that you've defined).
Refer to the "Implications for Custom Dependency Properties" section of XAML Loading and Dependency Properties for details
I have created a user control in WPF, and in the code behind I have created some dependency properties.
I added several WPF controls to my user control, one of the is a progress bar, so What I tried to do is to expose the Value progressBar property as below:
public static readonly DependencyProperty valueProperty = DependencyProperty.Register(
"Value",
typeof(Double),
typeof(MyUserControl),
new FrameworkPropertyMetadata(
ValuePropertyCallback));
private static void ValuePropertyCallback(DependencyObject controlInstance, DependencyPropertyChangedEventArgs args)
{
MyUserControl myUserControlInstance = (ProgressControl)controlInstance;
myUserControlInstance.progressBar.Value = (Double)args.NewValue;
}
public Double Value
{
get { return (Double)GetValue(valueProperty); }
set { SetValue(valueProperty, value); }
}
And in XAML I have written this:
<MyUserControl Name="myControl" Value="{Binding ProgressBarValue}" >
But It seems not to be working, neither setting nor getting the value.
I have a couple hours reviewing this but I cant realize what I am doing wrong.
Hope you can help me, Thank you in advance.
(Note: DataContext are defined previously and it is correct since this is the only binding that does not work)
valueProperty <----> "Value" does not match... (v/V) :=)
Have you tried Mode=TwoWay:
<MyUserControl Name="myControl" Value="{Binding ProgressBarValue, Mode=TwoWay}" >
I have also used PropertyMetadata instead of FrameworkPropertyMetadata
Try changing the name of your dependency property to be PascalCased:
ValueProperty
You might also want to look at BindsTwoWayByDefault to make sure changes to your DP are written to the source object.
Turns out that my problem was that I didnt implement the INotifyPropertyChanged interface, so, the changes I did were not showed. But since I am new at WPF using MVVM I didnt know that.
But you just need to create an ObservableObject, then your viewModel class has to inherit from it.
Here is an example to create the ObservableObject class and how to inherit from it.
I've created a UserControl which is essentially a button. It's got an Image and a Label on it and I've created two properties to set the Image's source and the Label's text like so:
public ImageSource Icon
{
get { return (ImageSource)this.GetValue(IconProperty); }
set { this.SetValue(IconProperty, value); icon.Source = value; }
}
public static readonly DependencyProperty IconProperty = DependencyProperty.Register("Icon", typeof(ImageSource), typeof(NavigationButton));
public string Text
{
get { return (string)this.GetValue(TextProperty); }
set { this.SetValue(TextProperty, value); label.Content = value; }
}
public static readonly DependencyProperty TextProperty = DependencyProperty.Register("Text", typeof(string), typeof(NavigationButton));
However, when I've added the control to my Page, the controls wont respond to any properties I set in XAML, e.g. <controls:MusicButton Icon="/SuCo;component/Resources/settings.png/> does nothing.
What am I doing wrong?
CLR properties that wrap dependency properties should never have any logic other than calling GetValue and SetValue. That is because they may not even be called. For example, the XAML compiler will optimize by calling GetValue/SetValue directly rather than using your CLR property.
If you need to execute some logic when a dependency property is changed, use metadata:
public ImageSource Icon
{
get { return (ImageSource)this.GetValue(IconProperty); }
set { this.SetValue(IconProperty, value); }
}
public static readonly DependencyProperty IconProperty = DependencyProperty.Register("Icon", typeof(ImageSource), typeof(NavigationButton), new FrameworkPropertyMetadata(OnIconChanged));
private static void OnIconChanged(DependencyObject dependencyObject, DependencyPropertyChangedEventArgs e)
{
//do whatever you want here - the first parameter is your DependencyObject
}
EDIT
In my first answer, I assumed your control's XAML (be it from a template or directly in a UserControl) is correctly hooked up to the properties. You haven't showed us that XAML, so it was perhaps an incorrect assumption. I'd expect to see something like:
<StackPanel>
<Image Source="{Binding Icon}"/>
<TextBlock Text="{Binding Text}"/>
</StackPanel>
And - importantly - your DataContext must be set to the control itself. You can do this in various different ways, but here is a very simple example of setting it from the code behind:
public YourControl()
{
InitializeComponent();
//bindings without an explicit source will look at their DataContext, which is this control
DataContext = this;
}
Have you tried setting the text property as well? The source of an image may just be wrong. Text is much more straight forward.
Also, in your example, you missed a quotation mark. So if it's copied from your real code, you may want to check that.
Barring those minor admittedly unlikely causes for your problem, I'd suggest setting the properties in code to check whether that has any effect. If it has, then you should really check your XAML.
Since you haven't posted the rest of your code, I can't really tell if you have problems somewhere else that might affect the control.
And yes, I know I'm not very helpful, but I've been working with WPF for only a little while. Hope it helps anyway.