set button datacontext to multiple elements - wpf

I've got a button that I need to be disabled when validation errors occur in my window. The items on which these errors can occur are all textboxes.
I've bound my Button's datacontext as such:
DataContext="{Binding ElementName=txtEmail}"
Now with this, I can set the button style to disabled when validation errors occur in the email textbox, but I want to do it also when it occurs in other textboxes in my window?
How can I set this binding to multiple textboxes?

You can't, at least not directly. You could use a MultiBinding with all of the desired text boxes as inputs, but you will need to provide an IMultiValueConverter to "combine" the various text boxes into one object (such as a list):
<Button>
<Button.DataContext>
<MultiBinding Converter="{StaticResource ListMaker}">
<Binding ElementName="txtEmail" />
<Binding ElementName="txtFirstName" />
<Binding ElementName="txtLastName" />
</MultiBinding>
</Button.DataContext>
</Button>
And it is then that resulting list object that will be passed to your trigger, so you won't be able to access the Validation.HasError property directly: your DataTrigger will also need to bring in a converter which converts the list object into a boolean indicating whether Validation.HasError is set for anything in the list. At this point you might as well just forget about triggers and bind IsEnabled using a MultiBinding:
<Button>
<Button.IsEnabled>
<MultiBinding Converter="{StaticResource AllFalse}">
<Binding Path="(Validation.HasError)" ElementName="txtEmail" />
<Binding Path="(Validation.HasError)" ElementName="txtFirstName" />
<Binding Path="(Validation.HasError)" ElementName="txtLastName" />
</MultiBinding>
</Button.DataContext>
</Button>
(Here the AllFalse converter returns true if all inputs are false, and false if any input is true.)
A better approach, however, may be, instead of binding the Button directly to other UI elements, have your data object -- the same object that your text boxes are binding to -- expose an IsValid property (with suitable change notifications), and bind your Button.IsEnabled to that:
<Button IsEnabled="{Binding IsValid}" />
This moves you towards a MVVM-style solution which helps with things like testability (e.g. it's easy to create tests for the IsValid property; it's much harder to create tests for Button.IsEnabled).

For the MVVM approach you could try implementing a command router from ICommand.
<Button Command="{Binding Path=Commands.MyButtonCommand}" Style="{StaticResource MyButtonStyle}" ></Button>
where the Commands property is part of the ViewModel. You then have control over what functionality the command implements as well as whether it is enabled or not. Testing is then a whole lot easier.

Related

WPF TextBlock MultiBinding

I want to bind TextBlock's Text property to some elements' and some model's properties. Something like this:
<TextBlock>
<TextBlock.Text>
<MultiBinding>
<Binding ElementName="myElement1" Mode="OneWay" Path="Text" />
<Binding ElementName="myElement2" Mode="OneWay" Path="Text" />
<Binding Mode="OneWay" Path="Property1" />
<Binding Mode="OneWay" Path="Property2" />
</MultiBinding>
</TextBlock.Text>
</TextBlock>
The TextBlock has a text value, combination of myElement1, myElement2 and Property1, Property2. There is not a problem. The text value is generated successfully.
Here is my question:
Can I bind whole (combined) text value of the TextBlock to another model's property, i.e. Property3, without code?
Not without some really bad hacking which would require writing some code to set up attached properties and other bindings anyway. The issue is that any binding has 2 ends: target and source. Since the target (where the binding is set) must be a DependencyProperty that means that your model must be on the source end of the binding you're trying to do. This isn't a problem as far as setting a value since TwoWay and OneWayToSource bindings do this just fine.
You have a bigger problem though in that the original place where the value is coming from (TextBlock.Text) already is assigned a binding and so can't be the target for your model binding. You might next want to try using another UIElement property as an intermediary to take the Text value and push it to the model. To do that you again need the model to be the source and the other UIElement property to be the target. But that same property also needs to be the target of a binding to the original Text property that you're trying to extract, so again you're stuck.
Bottom line is that you're much better off handling this in your Model and ViewModel layers rather than trying to force the stuff you have set up in XAML to be driving everything.

Dependency Property to fill list or array

I have a custom control. This has the ability to do something with several other Controls. I would like it to have an element NotifyControl where I can bind some other controls like NotifyControl="{Binding ElementName=controlA}". This is fine but I would like to write down n controls. So maybe a list in the element value or noting the element multiple times. Like
<MyControl NotifyControl="{Binding ElementName=a}" NotifiyControl="{Binding ElementName=b}" />
or
<MyControl NotifyControl="{Binding ElementName=a}, {Binding ElementName=b}" />
Which one is possible and how do to it? I got no luck with an array type, maybe my notation like above is wrong.
EDIT:
I now have
<MyControl>
<MyControl.NotifyControls>
<NotifyControlWrapper View="{Binding ElementName=details}" Test="entry one" />
<NotifyControlWrapper View="{Binding ElementName=gauge}" Test="e2" />
</MyControl.NotifyControls>
</MyControl>
<OtherControl x:Name="details" />
NotifyControls is a DependencyProperty and filled with two entries, so this part works fine. The source of NotifyControlWrapper is just a class derived from DependencyObject with the two dependency properties View (type INotifyControl) and Test (type String).
As I sayed my list gets two entries with two NotifyControlWrapper. But while Test contains the given String, View is null. Why is that or how to debug?
Neither one in your question is possible. You can't add the same property twice so #1 won't work. You can't add two bindings so #2 won't work. I would add a property NotifyControls as a List type. NotifyControl could still be available as a separate item or to add to the list of controls in NotifyControls. You can add items in Xaml:
<MyControl.NotifyControls>
<ControlWrapper Control="{Binding ElementName=a}"/>
<ControlWrapper Control="{Binding ElementName=b}"/>
</MyControl.NotifyControls>
ControlWrapper would just have a single member property, Control, so that you can specify the binding.
If N is fixed, you can use a MultiBinding (with a converter):
<MyControl>
<MyControl.NotifyControl>
<MultiBinding Converter="...">
<Binding ElementName="controlA" />
<Binding ElementName="controlB" />
<Binding ElementName="controlC" />
<Binding ElementName="controlD" />
<Binding ElementName="controlE" />
...
</MultiBinding>
</MyControl.NotifyControl>
</MyControl>
If N changes, an option would be to add an ObservableCollection<> to your class which you add/remove the controls to, and then bind to it (again, with a converter)
<MyControl NotifyControl="{Binding ElementName=ParentElement, Path=MyObservableCollection, Converter=...}" />

Can a WPF converter access the control to which it is bound?

Long version:
I have a simple WPF converter than does date conversions for me. The converter basically checks the date and formats it in dd/M/yyyy format. The converter does some smarts with the handling of the date which means that the user could type "23061971" and the value will be converted to "23/06/1971".
All this is trivial and working. The problem is that when I update the value, it does not update the caret position. Assume "|" is the caret and the user types "23061971|" then a millisecond later it is updated to "230619|71".
What I'd like to do is detect if the caret at the end of the value - if so, shift it to the end of the edit field once the new value has been updated. In order to do this, I'll need access to the edit control to which the converter is attached.
Short version:
From A WPF converter, can I get a reference to the control that is bound to that converter?
Here is an excellent article on how to get direct access to the control from within a converter: http://social.technet.microsoft.com/wiki/contents/articles/12423.wpfhowto-pass-and-use-a-control-in-it-s-own-valueconverter-for-convertconvertback.aspx
Essentially:
<MultiBinding Converter="{StaticResource MyConverter}" >
<Binding RelativeSource="{RelativeSource Self}" Mode="OneTime"/>
<Binding Path="MyValue2" />
</MultiBinding>
in the converter values[0] will be your control, ready for casting and values[1] would be the data that you are binding.
In a ValueConverter you can't get access to the control - however you can get access if you use a multibinding with a multivalueconverter.
In the multibinding the first binding is your binding as now - without the converter. The second binding you bind to the control itself - there you go acces to the control.
I have used this approach to gain other things also - you can make "dummy" bindings to properties you want to trigger updates, i.e. if you bind to the control itself you will only get updated if it changes, not if a property does - so create dummybindings for those.
You can send the control with the MultiBinding like this.
<TextBox Height="100" x:Name="textbox1" DockPanel.Dock="Top">
<TextBox.Text>
<MultiBinding Converter="{StaticResource MultiConverter}">
<Binding ElementName="textbox1" Path="." />
</MultiBinding>
</TextBox.Text>
</TextBox>
I don't thknk a converter has any way to get at the control that is using it. It is only a simple piece of logic that converts one object to another object.
However, in you case, perhaps you can trap the change event and then manually move the caret. If you think about it, caret position is strictly a view concern; it has nothing to do with converters or the data. You should not burden view-controller logic with it. You should definitely not burden converter logic (which is classified under utility classes) with it.

WPF Textbox Binding not Responding when ValidationRule Fired

I have a textbox that has a ValidationRule applied to it:
<TextBox Style="{StaticResource StandardTextBox}"
Grid.Column="1" Grid.Row="4"
IsReadOnly="{Binding SaveModeText}"
MaxLength="50">
<TextBox.Text>
<Binding Path="Individual.SurName"
UpdateSourceTrigger="PropertyChanged"
ValidatesOnDataErrors="True"
ValidatesOnExceptions="True"
NotifyOnValidationError="True">
<Binding.ValidationRules>
<valid:RequiredTextBoxValidationRule
ErrorMessage="Please enter a last name" />
</Binding.ValidationRules>
</Binding>
</TextBox.Text>
</TextBox>
When the page loads the textbox contains the correct value based on its binding. If I delete the value from the textbox the ValidationRule fires properly and I see the error message as expected. My application contains a "Discard Changes" button which reloads the DataContext. The hope was it would reset all of the bindings and once again this textbox would display the original value. For some reason, all other values on the page that do not have a ValidationRule associated with them get reset properly, but this textbox does not.
If I remove the ValidationRule from the XAML the value resets properly. If I handle validation through IDataErrorInfo, the validation fires properly and the value resets properly. Because I have used ValidationRules throughout my application, I was wondering if anyone had come across this issue and resolved it. At this point I would prefer to stick with the implemented ValidationRules if possible, instead of switching everything over to IDataErrorInfo.
Since your you are modifying the value in code, wouldn't you need to have Mode=TwoWay in your binding for it to update? I don't have time to dig in and see if that's what's wrong, but it may be a place to start.

How to determine WPF SelectedItem for a window

I have a WPF app with many list based controls in a window, which all are bound to different CollectionViews.
At the window level is there a way to get the current selected item for the currently in focus list based control? I know I can do this with some fairly trivial code by looking for the in focus element but does WPF support this as a concept out of the box?
Something like Window.CurrentSelectedDataItem would be great. I am looking into using this as a way to centralize command management for enabling disabling commands based on a current selected data item.
I don't think that there is a property like you specify, but as an alternative you could register a ClassHandler for the ListBox.SelectionChanged event in your Window class:
EventManager.RegisterClassHandler(typeof(ListBox), ListBox.SelectionChanged,
new SelectionChangedEventHandler(this.OnListBoxSelectionChanged));
This will get called whenever the selection changes in any ListBox in your application. You can use the sender argument to determine which ListBox it was that changed its selection, and cache this value for when you need it.
I haven't tried this, but you could try using a MultiBinding with a converter to get to the correct item:
<MultiBinding Converter="{StaticResource coalesce}">
<MultiBinding.Bindings>
<MultiBinding Converter="{StaticResource nullIfFalse}">
<MultiBinding.Bindings>
<Binding ElementName="List1" Path="HasFocus" />
<Binding ElementName="List1" Path="SelectedItem" />
nullIfFalse returns the second parameter, if the first is true, null otherwise. coalesce returns the first non-null element.

Resources