How do you get the WPF error template to appear on a control within a UserControl in WPF?
I have a UserControl containing two Labels, two TextBoxes, and a CheckBox. One of the TextBoxes represents the name of the entity and it is bound to a Name property off of a Model property exposed by my ViewModel, which is the DataContext of my Window. The Model class implements the IDataErrorInfo interface and I have confirmed through Unit Testing that when the Name is blank an error is returned through the property indexer implementation. I have bound to the Dependency Property backing the Name TextBox in my UserControl and when the validation error is encountered the WPF error template places a red border around the entire UserControl rather than just the Name TextBox.
The binding to the name field of the UserControl is as follows.
<vc:MyUserControl ItemName="{Binding Model.Name, ValidatesOnDataErrors=True}" />
A simiplified version of my UserControl and the backing DependencyProperty is as follows.
<UserControl>
<Grid>
<TextBox Text="{Binding ItemName}" />
</Grid>
</UserControl>
public partial class MyUserControl: UserControl
{
public static readonly DependencyProperty ItemNameProperty =
DependencyProperty.Register(
"ItemName",
typeof(string),
typeof(MyUserControl),
new FrameworkPropertyMetadata(string.Empty, FrameworkPropertyMetadataOptions.BindsTwoWayByDefault)
);
public string ItemName
{
get { return (string)GetValue(ItemNameProperty); }
set { SetValue(ItemNameProperty, value); }
}
}
The information I have found relating to this issue thus far has all been in regards to Silverlight or using a converter to not show the red border (which did not make sense to me). This information was all found here on stackoverflow.
Has anyone been able to solve this issue with WPF? Am I overlooking something obvious?
The ErrorTemplate for UserControl will be used if bindings to your UserControl use ValidatesOnDataErrors=True. But you can remove the red border with the Validation.ErrorTemplate Attached Property.
All controls within your UserControl will only show a red border if you validate their bindings by implementing IDataErrorInfo for the backing DependencyProperties too.
public class MyUserControl : UserControl, IDataErrorInfo
{
public static readonly DependencyProperty ItemNameProperty =
DependencyProperty.Register(
"ItemName",
typeof(string),
typeof(MyUserControl),
new FrameworkPropertyMetadata(string.Empty, FrameworkPropertyMetadataOptions.BindsTwoWayByDefault)
);
public string ItemName
{
get { return (string)GetValue(ItemNameProperty); }
set { SetValue(ItemNameProperty, value); }
}
public string Error
{
get { throw new NotImplementedException(); }
}
public string this[string columnName]
{
get
{
// use a specific validation or ask for UserControl Validation Error
return Validation.GetHasError(this) ? "UserControl has Error" : null;
}
}
}
and here the simplified XAML
<UserControl Validation.ErrorTemplate="{x:Null}">
<Grid DataContext="{Binding RelativeSource={RelativeSource AncestorType=UserControl}}">
<TextBox Text="{Binding ItemName, ValidatesOnDataErrors=True}" />
</Grid>
</UserControl>
Addition
If you want to differentiate between errors you can get the BindingExpression for your DependencyProperty and check the HasError Property.
BindingExpression be = BindingOperations.GetBindingExpression(this, ItemNameProperty);
return be != null && be.HasError ? "ItemName has Error" : null;
Related
I am trying (and failing) to do data binding on a dependency property in xaml. It works just fine when I use code behind, but not in xaml.
The user control is simply a TextBlock that bind to the dependency property:
<UserControl x:Class="WpfTest.MyControl" [...]>
<TextBlock Text="{Binding Test}" />
</UserControl>
And the dependency property is a simple string:
public static readonly DependencyProperty TestProperty
= DependencyProperty.Register("Test", typeof(string), typeof(MyControl), new PropertyMetadata("DEFAULT"));
public string Test
{
get { return (string)GetValue(TestProperty); }
set { SetValue(TestProperty, value); }
}
I have a regular property with the usual implementation of INotifyPropertyChanged in the main window.
private string _myText = "default";
public string MyText
{
get { return _myText; }
set { _myText = value; NotifyPropertyChanged(); }
}
So far so good. If I bind this property to a TextBlock on the main window everything works just fine. The text update properly if the MyText changes and all is well in the world.
<TextBlock Text="{Binding MyText}" />
However, if I do the same thing on my user control, nothing happens.
<local:MyControl x:Name="TheControl" Test="{Binding MyText}" />
And now the fun part is that if I do the very same binding in code behind it works!
TheControl.SetBinding(MyControl.TestProperty, new Binding
{
Source = DataContext,
Path = new PropertyPath("MyText"),
Mode = BindingMode.TwoWay
});
Why is it not working in xaml?
The dependency property declaration must look like this:
public static readonly DependencyProperty TestProperty =
DependencyProperty.Register(
nameof(Test),
typeof(string),
typeof(MyControl),
new PropertyMetadata("DEFAULT"));
public string Test
{
get { return (string)GetValue(TestProperty); }
set { SetValue(TestProperty, value); }
}
The binding in the UserControl's XAML must set the control instance as the source object, e.g. by setting the Bindings's RelativeSource property:
<UserControl x:Class="WpfTest.MyControl" ...>
<TextBlock Text="{Binding Test,
RelativeSource={RelativeSource AncestorType=UserControl}}"/>
</UserControl>
Also very important, never set the DataContext of a UserControl in its constructor. I'm sure there is something like
DataContext = this;
Remove it, as it effectively prevents inheriting a DataContext from the UserConrol's parent.
By setting Source = DataContext in the Binding in code behind you are explicitly setting a binding source, while in
<local:MyControl Test="{Binding MyText}" />
the binding source implicitly is the current DataContext. However, that DataContext has been set by the assignment in the UserControl's constructor to the UserControl itself, and is not the inherited DataContext (i.e. the view model instance) from the window.
I got a custom TextBox which I plan to include in another UserControl, however when setting up the Binding for it, it simply just doesn't bind.
I simplified the code for clarity.
My custom TextBox:
<UserControl DataContext="{Binding RelativeSource={RelativeSource Self}}">
<TextBox Text="{Binding Text, UpdateSourceTrigger=PropertyChanged}" />
</UserControl>
partial class CustomTextBox : UserControl
{
public string Text
{
get { return (string)GetValue(TextProperty); }
set
{
SetValue(TextProperty, value);
}
}
public static readonly DependencyProperty TextProperty = DependencyProperty.Register(
"Text",
typeof(string),
typeof(CustomTextBox),
new PropertyMetadata(String.Empty));
}
This binding works as expected. When using CustomTextBox in another UserControl or Window, I can access the property just as expected.
The following code blocks describe the UserControl that uses CustomTextBox and the corresponding ViewModel with the property I want to bind Text to.
<UserControl>
<UserControl.DataContext>
<vm:MyViewModel />
</UserControl.DataContext>
<local:CustomTextBox Text="{Binding FooBar, UpdateSourceTrigger=PropertyChanged}" />
</UserControl>
public class MyViewModel : INotifyPropertyChanged
{
private string _fooBar;
public string FooBar
{
get { return _fooBar = (_fooBar ?? ""); }
set
{
_fooBar = value; OnPropertyChanged();
}
}
public event PropertyChangedEventHandler PropertyChanged;
}
My problem occurs exactly when I want to bind the Text property to a ViewModel in another UserControl, it just doesn't work. In this case I tried to bind the Text property to the FooBar property on the MyViewModel class, however changes to the Text property do not get reflected on the FooBar property and vice-versa. However when I hover over the binding in the XAML view, it shows the type of the property, so I don't exactly see what's wrong here.
My best guess is that it has to do with two bindings accessing the same property.
modify DP registration to include FrameworkPropertyMetadataOptions.BindsTwoWayByDefault option
public static readonly DependencyProperty TextProperty = DependencyProperty.Register(
"Text",
typeof(string),
typeof(CustomTextBox),
new FrameworkPropertyMetadata(String.Empty, FrameworkPropertyMetadataOptions.BindsTwoWayByDefault));
I try to develop a UserControl look like a TextBox white two different changes.
First of all the new TextBox has to display a "PlaceholderText" if the TextBox text value is empty. My solution for this implementation includes a second TextBox white the "PlaceholderText" as simply Text Attribute. At last I changed the visibility an the focus to the other TextBox.
An when the Textbox ValidationResult Object return false they display a TextBlock white an "ErrorMessage"
They tow implementations are already working and existent. For my new TextBox I copied all the TextBox specific properties into my new control and passed them to the original TextBox.
Now I tried to bind the Text property from my new control to a DependencyPropery Object (in the ViewModel).
My implementation looks this:
Custom TextBox Text property
public string Text
{
get => TbSource.Text;
set => TbSource.Text = value;
}
ViewModel propdp
public static DependencyProperty PersonProperty =
DependencyProperty.Register(nameof(Person), typeof(Person), typeof(PersonViewModel));
public Person Person
{
get => (Person)GetValue(PersonProperty);
set => SetValue(PersonProperty, value);
}
And my view
<customControl:NiceTextBox Grid.Row="0" Grid.Column="1" IsPlaceholderAktive="True" PlaceholderText="Enter first name" ErrorMessage="The given first name isn't valid." Text="{Binding Person.Name}" />
Now in the implementation in the View I became follow message:
Has anyone an idea how to fix it? I tried to change my Text property to a dependency property but then I can't pass the input and output from the TbSource.
The Text property of your custom control - the target property - must be a dependency property for you to be able to bind to it like this in XAML:
<customControl:NiceTextBox ... Text="{Binding Person.Name}" />
But the Person property in the view model - the source property - shouldn't be defined as a dependency property.
So you have defined the dependency property in the wrong class. Only target properties must be defined as dependency property for you to be able to bind them to some source property.
A control inherits from a DependencyObject class where the GetValue and SetValue methods are defined but a view model generally doesn't.
Make your UserControl Text property as DependencyProperty and the property in ViewModel as a normal CLR property and bind it.
UserControl
public string Text
{
get { return (string)GetValue(TextProperty); }
set { SetValue(TextProperty, value); }
}
public static readonly DependencyProperty TextProperty =
DependencyProperty.Register("Text", typeof(string), typeof(NiceTextBox), new PropertyMetadata(string.Empty));
ViewModel
public Person Person { get; set; }
XAML
<customControl:NiceTextBox ... Text="{Binding Person.Name}" />
I have creted my User Control where I would like to make posibility to bind a UIElement. My user control:
public partial class TextArea : UserControl
{
public UIElement AncestorContainer
{
get => (UIElement)GetValue(AncestorContainerProperty);
set => SetValue(AncestorContainerProperty, value);
}
public TextArea()
{
InitializeComponent();
DataContext = this;
}
public static readonly DependencyProperty AncestorContainerProperty =
DependencyProperty.Register("AncestorContainerProperty", typeof(UIElement), typeof(TextArea), new PropertyMetadata(null));
}
When creating my UserControl in C# it is working fine - no exceptions like this:
var textArea = new TextArea
{
AncestorContainer = Root, // Root is name of Grid
Text = textItem.Text
};
However when trying to use binding in XAML I get an exception:
<ItemsControl ItemsSource="{Binding SuggestedTexts}" >
<ItemsControl.ItemTemplate>
<DataTemplate>
<components:TextArea
AncestorContainer="{Binding ElementName=Sidebar}"/> <!-- Side bar is name of Grid above in XAML -->
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
And the exception:
"Binding" cannot be set in the "ParentContainer" type "TextArea".
"Binding" can only be set in the properties of the DependencyProperty
object DependencyObject.
You have a typo declaring dependency property as you have written
DependencyProperty.Register("AncestorContainerProperty", ...
which should be replaced by
DependencyProperty.Register("AncestorContainer", ...
or better
DependencyProperty.Register(nameof(AncestorContainer), ...
I have created the following User Control:
<UserControl x:Class="TextBinder" ...>
<TextBox Text="{Binding ????}" />
</UserControl>
Now I am using my user control twice in my MainWindow. The MainWindow is then bound to my ViewModel (I set the DataContext). Now the problem is: how can I bind my user controls to the user_controlViewModel?
In my ViewModel, I have created two objects let's call them UC_1 and UC_2, they contain different texts and I would like to bind them to their respective user control in my MainWindow.
What should I put at ????
Note: please do not simplify mu TextBox to double textboxes in one usercontrol. This is not what I would like since in my real life example I have more stuff than textbox only and the usercontrol should be used multiple times in one view.
Thanks!
i gave you a general answer:
within a "real(a usercontrol you wanna use with different viewmodels with different property names)" usercontrol you bind just to your own DependencyProperties and you do that with ElementName or RelativeSource binding and you should never set the DataContext within a UserControl.
<UserControl x:Name="myRealUC" x:class="MyUserControl">
<TextBox Text="{Binding ElementName=myRealUC, Path=MyOwnDPIDeclaredInMyUc, Path=TwoWay}"/>
<UserControl>
if you do that you can easily use this Usercontrol in any view like:
<myControls:MyUserControl MyOwnDPIDeclaredInMyUc="{Binding MyPropertyInMyViewmodel}"/>
and for completeness: the Dependency Property
public readonly static DependencyProperty MyOwnDPIDeclaredInMyUcProperty = DependencyProperty.Register(
"MyOwnDPIDeclaredInMyUc", typeof(string), typeof(MyUserControl), new PropertyMetadata(""));
public bool MyOwnDPIDeclaredInMyUc
{
get { return (string)GetValue(MyOwnDPIDeclaredInMyUcProperty); }
set { SetValue(MyOwnDPIDeclaredInMyUcProperty, value); }
}
Thats right, you need yo declare a dependency property in your UserControl:
public partial class TextBinder:UserControl
{
public static readonly DependencyProperty textproperty =
DependencyProperty.Register("Text", typeof(string), typeof(TextBinder));
public string Text
{
get
{
return this.GetValue(textproperty) as string;
}
set
{
this.SetValue(textproperty,value);
}
}
}
And then, you can use your usercontrol in your window at this way:
<YourNamespace:TextBinder Text={Binding ViewModelProperty}/>