I know that I can declare a new DependencyProperty as such:
public String PropertyPath
{
get { return (String)GetValue(PropertyPathProperty); }
set { SetValue(PropertyPathProperty, value); }
}
public static readonly DependencyProperty PropertyPathProperty =
DependencyProperty.Register(nameof(PropertyPath), typeof(String),
typeof(NotEmptyStringTextBox),
new FrameworkPropertyMetadata(PropertyPath_PropertyChanged));
protected static void PropertyPath_PropertyChanged(DependencyObject d,
DependencyPropertyChangedEventArgs e)
{
var ctl = d as NotEmptyStringTextBox;
var binding = new Binding(ctl.PropertyPath)
{
ValidationRules = { new NotEmptyStringRule() },
// Optional. With this, the bound property will be updated and validation
// will be applied on every keystroke.
UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged
};
ctl.StringBox.SetBinding(TextBox.TextProperty, binding);
}
But then the UserControl can only recieve a string with the name of the property to bind, and bind to it.
What I would like is to be able to have the same kind of comportment as "classical" properties, which you can either bind to, or give a static value.
My usage would be a boolean that modifies the display state of a UserControl, either statically with a fixed value or dynamically with a binding, all depending on the use case.
Maybe the way I made my dependency Property in the first place is incorrect, but here is how I can use it:
<inputboxes:NotEmptyStringTextBox
Grid.Column="1"
PropertyPath="Name"/>
This will bind the "Name" property from the DataContext, but I can't use it with a raw string, as it will make a BindingExpression error: "property not found"
EDIT:
I now have tried the following:
public bool Test
{
get { return (bool)GetValue(TestProperty); }
set { SetValue(TestProperty, value); }
}
public static readonly DependencyProperty TestProperty =
DependencyProperty.Register(nameof(Test), typeof(bool),
typeof(DamageTemplateListEditableUserControl));
I declared this new property, but I still cannot bind anything to it, only raw values are accepted
You shouldn't create a new binding in the callback. In fact, you don't need any callback at all.
Rename the dependency property to something better like "Text" and just bind the Text property of StringBox to the current value of your dependency property like this:
<TextBox x:Name="StringBox"
Text="{Binding Text, RelativeSource={RelativeSource AncestorType=local:NotEmptyStringTextBox},
UpdateSourceTrigger=PropertyChanged}" />
You can then set or bind the dependency property as usual.
If you really want a "PropertyPath" property, it shouldn't be a dependency property that you can bind something to but rather a simple CLR property that you can set to a string that represents a name of a property to bind to.
This is for example how the DisplayMemberPath property of an ItemsControl is implemented.
Related
I have a WPF control that is based on the TextBox control:
public class DecimalTextBox : TextBox
I have a dependency property that is bound to, which manages the numeric value, and is responsible for setting the Text property:
public decimal NumericValue
{
get { return (decimal)GetValue(NumericValueProperty); }
set
{
if (NumericValue != value)
{
SetValue(NumericValueProperty, value);
SetValue(TextProperty, NumericValue.ToString());
System.Diagnostics.Debug.WriteLine($"NumericValue Set to: {value}, formatted: {Text}");
}
}
}
protected override void OnTextChanged(TextChangedEventArgs e)
{
base.OnTextChanged(e);
if (decimal.TryParse(Text, out decimal num))
{
SetValue(NumericValueProperty, num);
}
}
This works well when entering a value into the textbox itself (it updates the underlying values, etc...). However, when the bound property of NumericValue is changed, despite updating the NumericValue DP, the Text property is not updated. In the tests that I've done, it would appear that the reason for this is that the set method above is not called when the bound value is updated. The binding in question looks like this:
<myControls:DecimalTextBox NumericValue="{Binding Path=MyValue, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"/>
Can anyone point me in the right direction as to why this property setter is not firing, or is there a better way to approach this?
As explained in Custom Dependency Properties and XAML Loading and Dependency Properties, you should not call anything else than GetValue and SetValue in the CLR wrapper of a dependency property:
Because the current WPF implementation of the XAML processor behavior for property setting bypasses the wrappers entirely, you should not put any additional logic into the set definitions of the wrapper for your custom dependency property. If you put such logic in the set definition, then the logic will not be executed when the property is set in XAML rather than in code.
In order to get notified about value changes, you'll have to register a PropertyChangedCallback with the dependency property metadata.
public static readonly DependencyProperty NumericValueProperty =
DependencyProperty.Register(
"NumericValue", typeof(decimal), typeof(DecimalTextBox),
new PropertyMetadata(NumericValuePropertyChanged));
public decimal NumericValue
{
get { return (decimal)GetValue(NumericValueProperty); }
set { SetValue(NumericValueProperty, value); }
}
private static void NumericValuePropertyChanged(
DependencyObject obj, DependencyPropertyChangedEventArgs e)
{
var textBox = (DecimalTextBox)obj;
textBox.Text = e.NewValue.ToString();
}
The WPF binding is not actually using your getter and setter, but instead directly interacts with the dependency property NumericValueProperty. In order to update the text, subscribe to the PropertyChanged event of the NumericValueProperty instead of trying to do anything special in the setter.
Subscribe to the change in your DependencyProperty definition, similar to the following:
// Using a DependencyProperty as the backing store for NumericValue. This enables animation, styling, binding, etc...
public static readonly DependencyProperty NumericValueProperty =
DependencyProperty.Register("NumericValue", typeof(decimal), typeof(DecimalTextBox), new FrameworkPropertyMetadata(0.0m, new PropertyChangedCallback(OnNumericValueChanged)));
private static void OnNumericValueChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
var self = d as DecimalTextBox;
// if the new numeric value is different from the text value, update the text
}
In my WPF application, we have extended the DataGridTextColumn with a class named SampleTextBoxColumn, and created a dependency property Sample inside it.
Example
public class SampleTextBoxColumn : DataGridTextColumn
{
public static readonly DependencyProperty SampleProperty =
DependencyProperty.Register("Sample", typeof(object), typeof(SampleTextBoxColumn), new FrameworkPropertyMetadata(null));
public object Sample
{
get { return (object)GetValue(SampleProperty); }
set { SetValue(SampleProperty, value); }
}
}
Now in XAML, I want to set value of this property Sample depending upon conditions i.e. want to set this property inside DataTrigger.
Now Since .net does not provide a way to style the DataGridColumn, So I am not able to do this.
Or, in generic, How can we set Dependency Property of DataGridTextColumn in Style.
Is there a way to set ValidatesOnDataErrors to True for my custom DependencyProperty, so I do not have to do that every time I bind to it?
Something in the lines of this.
public static readonly DependencyProperty TextProperty =
DependencyProperty.Register(nameof(Text), typeof(string),
typeof(ErrorTextEdit), new FrameworkPropertyMetadata(null)
{
BindsTwoWayByDefault = true,
DefaultUpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged,
// Something Here maybe???
});
public string Text
{
get { return (string) GetValue(TextProperty); }
set { SetValue(TextProperty, value); }
}
My control could also inherit from TextBox if that can help.
No, I am afraid not. This is a property of the Binding class rather than of the dependency property. What you could to is to replace the {Binding} markup extension in your XAML markup with a custom markup extension that sets the ValidatesOnDataErrors property for you:
How can i change the default values of the Binding Option in WPF?
Or create a custom binding class:
public class CustomBinding : Binding
{
public CustomBinding(string path)
:base(path)
{
this.NotifyOnValidationError = true;
}
}
Usage:
<TextBlock Text="{local:CustomBinding Name}" />
I'm working with a custom control that has several user-defined dependency properties. I'm running into the same issue described in this question.
My control is setting the default value of a custom dependency property in its constructor. When I use the control in a DataTemplate, the value set in the constructor is always used, even if I try to set it in XAML.
The answer to the linked question explains that the value set in the C# code has a higher priority, and a better approach would be to specify the default value in the dependency property's metadata.
In my case, I can't specify a default because the dependency property doesn't have a single default value that applies in all cases. The default values depend on another property, so I must look them up when the control is created and not when the property is registered.
Here's some code to help illustrate my problem:
public partial class MyControl : UserControl
{
public static readonly DependencyProperty MyProperty =
DependencyProperty.Register(
"MyProperty",
typeof(int),
typeof(MyControl),
new FrameworkPropertyMetadata(
int.MinValue,
FrameworkPropertyMetadataOptions.None,
new PropertyChangedCallback("OnMyPropertyChanged")));
public MyControl() : base()
{
InitializeComponent();
this.MyProperty = GetDefaultPropertyValue();
}
public int MyProperty
{
get { return (int)GetValue(MyProperty); }
set { SetValue(MyProperty, value); }
}
private int GetDefaultPropertyValue()
{
// look up the appropriate default based on some other criteria
return 42;
// (in reality, the default value for "MyProperty"
// depends on the value of a "Mode" custom DependencyProperty.
// this is just hard coded for testing)
}
}
The XAML usage looks something like this:
<!-- View displays 4 (desired) -->
<local:MyControl MyProperty="4" />
<!-- View displays default of 42 (desired) -->
<local:MyControl />
<!-- View displays default of 42 (wanted 4) -->
<DataTemplate x:Key="MyTemplate">
<local:MyControl MyProperty="4"/>
</DataTemplate>
To summarize:
The desired behavior is that the value from XAML is used first. If the value is not specified in the XAML, then I would like to fallback to the default value set in the control's constructor.
If I just include the control directly in a view, I get the expected behavior. If the control is used inside a DataTemplate, then I always get the default set in the constructor (even when the data template explicitly sets another value).
Is there any other way to specify the default value when the control is used in a template? The only option I can think of is to break the control up into several separate but similar controls, each of which uses a default value that is registered with the dependency property (which removes the need to have the default set based on the a Mode property).
Setting the default value in OnApplyTemplate while adding a small check should solve this:
public override void OnApplyTemplate()
{
base.OnApplyTemplate();
// Only set the default value if no value is set.
if (MyProperty == (int)MyPropertyProperty.DefaultMetadata.DefaultValue)
{
this.MyProperty = GetDefaultPropertyValue();
}
}
Please note that although this will work, it's not ideal since setting the property's value by code will essentially clear any data bindings for this property. For example, the following binding will no longer work once you call MyProperty = 42 in code:
<local:MyControl MyProperty="{Binding SomeProperty}" />
It should be possible to set the value while maintaining any bindings by using SetCurrentValue(MyPropertyProperty, GetDefaultPropertyValue()); to modify the property instead of MyProperty = GetDefaultPropertyValue(), but I'm not sure I like that too much either.
A better solution
What I would do is introduce a new read-only property in addition to the existing one, which will act as a calculated property. For example:
private static readonly DependencyPropertyKey MyCalculatedPropertyPropertyKey =
DependencyProperty.RegisterReadOnly("MyCalculatedProperty", typeof(int), typeof(MyControl),
new PropertyMetadata(int.MinValue));
public static readonly DependencyProperty MyCalculatedPropertyProperty = MyCalculatedPropertyPropertyKey.DependencyProperty;
public int MyCalculatedProperty
{
get { return (int)GetValue(MyCalculatedPropertyProperty); }
private set { SetValue(MyCalculatedPropertyPropertyKey, value); }
}
private static void OnMyPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
((MyControl)d).MyCalculatedProperty = (int)e.NewValue;
}
public MyControl()
: base()
{
InitializeComponent();
MyCalculatedProperty = GetDefaultPropertyValue();
}
I would like to disable column reording in a control we have created that is derived from ListView. This control is called a SortableListView. I thought a dependency property would be the best way to implement this, but the ((SortableListVIew)source).View is returning null. Here is the code:
public class SortableListView : ListView
{
// ...lots of other properties here
public static readonly DependencyProperty AllowsColumnReorderProperty =
DependencyProperty.Register(
"AllowsColumnReorder",
typeof(bool),
typeof(SortableListView),
new UIPropertyMetadata(true, AllowsColumnReorderPropertyChanged));
public bool AllowsColumnReorder
{
get
{
return (bool)this.GetValue(AllowsColumnReorderProperty);
}
set
{
this.SetValue(AllowsColumnReorderProperty, value);
}
}
private static void AllowsColumnReorderPropertyChanged(DependencyObject source, DependencyPropertyChangedEventArgs e)
{
ViewBase vb = ((SortableListView)source).View;
if (vb != null)
{
((GridView)vb).AllowsColumnReorder = (bool)e.NewValue;
}
}
And the XAML:
<TableControls:SortableListView x:Name="QueueViewTable" Margin="0,0,0,0"
Style="{StaticResource ListViewStyle}"
ItemsSource="{Binding Path=QueueList}"
ItemContainerStyle="{StaticResource alternatingListViewItemStyle}"
AlternationCount="2"
SelectionMode="Single"
SortEnabled="False"
AllowsColumnReorder="false">
The trouble is that vb is always null so the method fails to set AllowsColumnReoder. I am quite sure that the cast is valid because the code originally looked like this in OnInitialized:
((GridView)this.View).AllowsColumnReorder = false;
...but I need to set the AllowsColumnReorder on a particular instance of the view so this code is no good.
Can anyone tell me what I'm doing wrong? Or is there a better way to set this property?
The View property of ListView is itself a dependency property that could change. It appears to not be set yet when you're setting your property?
You may have to override the View property in your sortable list view, so you can add a property change listener, and then apply your sort property when the view itself gets set?
in wpf, you can override a dependency property declared in a parent class, shown here: http://msdn.microsoft.com/en-us/library/ms754209.aspx
you'd override the metadata for the View property, and in the PropertyMetadata param you set there, you can pass a function like you are above for AllowsColumnReorderPropertyChanged
in that handler, you'd check to see if the new view is a gridview, and then set your property.
that way, the either order of AllowsColumnReorder or View getting set will properly set your property.