Dependency Property to fill list or array - wpf

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=...}" />

Related

Setting dependency properties on a static value converter from XAML

I have a value converter I wrote that allows me to bind against a property, test that property against a given (hard-coded) value, and return a brush based on if the test was true or false. The converter inherits from DependencyObject and implements IValueConverter. It exposes two dependency properties called PositiveBrush and NegativeBrush.
I declare it in XAML like this:
<UserControl.Resources>
<xyz:CBrushConverter x:Key="BrushConverter"
PositiveBrush="{DynamicResource Glyph.Resource.Brush.LightGreen}"
NegativeBrush="{DynamicResource Glyph.Resource.Brush.DarkGray}" />
</UserControl.Resources>
I can then adjust the color of a given element like this:
<TextBlock Foreground="{Binding SomeProperty, ConverterParameter='SomeValue', Converter={StaticResource BrushConverter}}" />
So in this example (making the assumption that SomeProperty returns a string) if the bound property 'SomeProperty' matches 'SomeValue' the converter will return the PositiveBrush as the Foreground (otherwise it will return the NegativeBrush).
So far so good - There may be other ways to skin this cat; but this has served me well for a long time and I don't really want to rock the boat.
What I would like to do however is declare my Positive and Negative brushes as part of my binding expression. Right now, if I wanted to use Red/Green and Blue/Yellow color combinations, I would need to declare two BrushConverters. But if I could declare the Positive/Negative brushes as part of the binding expression, I could use the same converter.
In pseudo-code, something like this (obviously this doesn't work):
<Grid Foreground="{Binding SomeProperty, ConverterParameter='SomeValue', Converter={StaticResource BrushConverter, BrushConverter.PositiveBrush='Red', BrushConverter.NegativeBrush='Green'}}" />
I did find a similar question on stack, How can I set a dependency property on a static resource? but it didn't explicitly address my question.
So... my google-foo is weak - I wasn't able to come up with the right search terms to dissect the Xaml binding syntax and work this out on my own, if it is even possible.
As always, any help is appreciated!
This should work:
<TextBlock>
<TextBlock.Foreground>
<Binding Path="SomeProperty" ConverterParameter="SomeValue">
<Binding.Converter>
<xyz:CBrushConverter PositiveBrush="Red" NegativeBrush="Green"/>
</Binding.Converter>
</Binding>
</TextBlock.Foreground>
</TextBlock>
Note however that you don't use the converter as static resource here. You would create a new converter instance for each Binding.
But if I could declare the Positive/Negative brushes as part of the binding expression, I could use the same converter.
You can't really do this. Converter is just a property of the Binding class. You still need to create an instance of the converter and set the dependency properties of this particular instance. What if you have several bindings that uses the same converter instance with different values for the PositiveBrush and NegativeBrush properties simultaneously?
You could define a converter instance inline though:
<TextBlock>
<TextBlock.Foreground>
<Binding Path="SomeProperty" ConverterParameter="SomeValue">
<Binding.Converter>
<xyz:CBrushConverter PositiveBrush="Green" NegativeBrush="Red" />
</Binding.Converter>
</Binding>
</TextBlock.Foreground>
</TextBlock>

Make ViewModel property available for binding to IsChecked

I'm using Caliburn.Micro in my app. What I want to do is:
Create one RadioButton per available licence in the View
Check the one whose licence is currently active
So far I have two properties on my ViewModel (I'm leaving out INotify...Changed and its implementations here because that works):
BindableCollection<LicenceInfo> AvailableLicences { get; set; }
LicenceInfo ActiveLicence { get; set; }
In the ViewModel's constructor, I populate AvailableLicences and ActiveLicence. So far, so good.
Currently in the View itself, I have an ItemsControl which contains the RadioButtons and an invisible FrameworkElement to pass to MyConverter, where I extract the DataContexts of Self and the invisible FrameworkElement (whose DataContext is bound to the ViewModel) and compare them with (overridden) LicenceInfo.Equals():
<FrameworkElement Name="ActiveLicence" Visibility="Collapsed" />
<ItemsControl Name="AvailableLicences">
<ItemsControl.ItemTemplate>
<DataTemplate>
<RadioButton cal:Message.Attach="[Event Checked] = [Action ChangeActiveLicence($dataContext)]">
<RadioButton.IsChecked>
<MultiBinding Converter="{StaticResource MyConverter}" Mode="OneWay">
<Binding RelativeSource="{RelativeSource Self}" />
<Binding ElementName="ActiveLicence" />
</MultiBinding>
</RadioButton.IsChecked>
[...]
This actually works as intended, but it seems to me like an ugly workaround and I'm sure that I'm missing something.
Using <Binding x:Name="ActiveLicence" /> or <Binding Path="ActiveLicence" /> as the second parameter and removing the invisible FrameworkElement does not work, the ViewModel property is not being attached to the binding.
I'm not necessarily tied to using a MultiBinding. Anything similar to the Caliburn.Micro action like the one handling the Checked event would be welcome too. Any ideas?
From my point of view, you're pretty close to a good solution here, if adding a flag on the LicenceViewModel is not an option:
Instead of using the container framework element, try the following multi binding:
<MultiBinding Converter="{StaticResource MyConverter}" Mode="OneWay">
<Binding Path="DataContext" RelativeSource="{RelativeSource Self}" />
<Binding Path="DataContext.ActiveLicense" RelativeSource="{RelativeSource FindAncestor, AncestorType=ItemsControl}" />
</MultiBinding>
Modify the converter to compare two objects using Equals(), agnostic of the concrete type. That way, you're not messing around with unnecessary objects, still separating Views and ViewModels properly.
EDIT:
Regarding the alternative solution with a flag: I didn't notice, there is no LicenseViewModel involved in your code... Adding a flag to License info is not a good solution, I agree. You can consider to wrap the LicenseInfos inside LicenseInfoViewModels, though this would require a bit of infrastructure for the synchronization between the original collection of LicenseInfos on the model and the collection containing the ViewModels.
I have posted an extensive answer on that topic here.
Then you could set the flag of the active license's ViewModel to true and all others to false, when the ActiveLicense property changes.
It's a question of the specific context, whether it makes sense to go the extra mile here. If you don't plan to extend features over time etc, and it's just a simple selection of licenses, the first solution is sufficient, probably.

Is it possible to use a DynamicResource in a MultiBinding at all?

In this case I am looking to use strings declared in a resource dictionary as part of a binding on a Text property. Binding just a single dynamic resource string is not a problem:
<TextBlock Text="{DynamicResource keyToMyString}" />
But you quickly run into problems if you need to use a StringFormat on a MultiBinding because you need to insert dynamic text or want to combine several strings. For example, if my MultiBinding looks like this:
<TextBlock.Text>
<MultiBinding StringFormat="{}{0} {1} some more text">
<Binding Source="{x:Static Resources:Strings.string1}" />
<Binding Source="{x:Static Resources:Strings.string2}" />
</MultiBinding>
<TextBlock.Text>
I can inject string1 and string2 from the specified resource file into the bound text, no problems there. But I cannot find a way to use strings from a dynamic resource in the same way. (I'm using this method to inject company and product names into text from a merged resource dictionary).
With a TextBlock I can circumvent this issue by using several Run items for the TextBlock content (reference):
<TextBlock >
<Run Text="{DynamicResource CompanyName}" />
<Run Text="{DynamicResource ProductName}" />
<Run Text="{DynamicResource MajorVersion}" />
</TextBlock>
but this is of no help when needing to bind the dynamic resource to the Window Title property. Is there anyway to accomplish this with (creative, if necessary) use of the existing markup extensions (like x:Static, etc)? Or do we have to write our own markup extension to achieve this?
Dynamic resource references have some notable restrictions. At least one of the following must be true:
The property being set must be a property on a FrameworkElement or FrameworkContentElement. That property must be backed by a DependencyProperty.
The reference is for a value within a Style Setter.
The property being set must be a property on a Freezable that is provided as a value of either a FrameworkElement or FrameworkContentElement property, or a Setter value.
Source: XAML Resources, MSDN.
So, in case of using the Binding, all the statements are violated.
As was shown, the DynamicResourceExtension works just fine for an instance of the Run class because the Run class (at least) is derived from the FrameworkContentElement class.
Additional references
Resources section: Wha' Happened Part Two: More Property Changes in WPF.
WPF: Dependency Properties & Resources.

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.

set button datacontext to multiple elements

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.

Resources