Silverlight: Select control based on list count - silverlight

I'm bind a Telerik RadGridView to a List<MyObject> myList = new List<MyObject>. But if the myList.Count == 0 (the list is empty ;) ) I want to show another control to the user.
I know I could use some visibility converter, but I prefer achieving this in XAML.
Thank you

I think that value converters are your only choice here :)
However, I've found out that if you structure them properly, value converters are great.
Here are a couple of good tools for this:
A Generic Boolean Value Converter
Linking Multiple Value Converters in WPF and Silverlight
With these tools in mind, I would go with something like this:
<Grid>
<telerik:RadGridView ItemsSource="{Binding myList}">
<telerik:RadGridView.Visibility>
<Binding Path="myList">
<Binding.Converter>
<converters:SequentialValueConverter>
<converters:IsEmptyConverter />
<converters:BooleanToVisibilityConverter TrueValue="Collapsed" FalseValue="Visible" />
</converters:SequentialValueConverter>
</Binding.Converter>
</Binding>
</telerik:RadGridView.Visibility>
</telerik:RadGridView>
<YourControl>
<YourControl.Visibility>
<Binding Path="myList">
<Binding.Converter>
<converters:SequentialValueConverter>
<converters:IsEmptyConverter />
<converters:BooleanToVisibilityConverter TrueValue="Visible" FalseValue="Collapsed" />
</converters:SequentialValueConverter>
</Binding.Converter>
</Binding>
</YourControl.Visibility>
</YourControl>
</Grid>
Also, as Jason said, myList needs to be an ObservableCollection so the gui gets notified when it changes.
Hope it helps!

If you switched to ObservableCollection<MyObject> you can bind using VisibilityConverters to that your myList.Count all in XAML. If you are having issues because you are setting the ItemsSource in codebehind, you may want to have it be a resource or switch to something more MVVM.

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.

Can I data bind to a indexed property where a property of the parent is the index

Using WPF with MVVM, my VM has an indexed property
IObject1 this[string key]
I need to bind a property of the view to a property of IObject1, and the key of the object1 that I need is the name of the control in the view. Essentially I need nested bindings
<TextBlock x:Name="Key1" Text="{Binding ["Key1"].DisplayText}
but, the name will very for different items so I need the nested binding
<TextBlock x:Name="Key1" Text="{Binding [{Binding Name, RelativeSource={RelativeSource Self}].DisplayText}
My actual case is more complicated than this, but if I can get this far I think that I can figure out the rest.
I'm using Blend, and I'd love a way to teach my designer to do this type of thing within Blend, but I'm happy to use code if I need to.
Am I overlooking something obvious? I can't figure out how to do this and I haven't stumbled upon the correct Google / Stack Overflow search term.
Thanks.
That's a weird solution lol, anyhose, you can solve it with MultiBinding & converters.
<TextBlock.Text>
<MultiBinding Converter={StaticResource combine}>
<Binding Path=Dictionary />
<Binding Path=Name />
</Multibinding>

Databinding issue with textbox and accessors

I am wondering what am I missing? The binding is not displaying at all in the textbox. These are my codes:
XAML Namespace:
xmlns:c="clr-namespace:mySystem.Workspace"
DataContext and Resources:
<Grid.Resources>
<c:Parameter x:Key="mySource"/>
</Grid.Resources>
<Canvas>
<Canvas.DataContext>
<Binding Source="{StaticResource mySource}" />
</Canvas.DataContext>
Textbox:
<TextBox x:Name="TextBox" Width="159" Height="26" Canvas.Left="36" Canvas.Top="47">
<TextBox.Text>
<Binding Path="JobKey" Mode="TwoWay" UpdateSourceTrigger="PropertyChanged"/>
</TextBox.Text>
The class:
namespace mySystem.Workspace
{
public class Parameter : Object
{
The accessors:
public BasePar JobKey
{
get { return jobKey; }
set { jobKey = value; }
}
There are lots of odd things here but the most obvious one that will get you working is that the Binding Path is case sensitive.
Change your binding to:
<Binding Path="JobKey" Mode="TwoWay" UpdateSourceTrigger="PropertyChanged"/>
This should get the binding working.
I'm also not sure what type BasePar is, or is meant to be, but unless you are doing something clever intentionally, just make it a standard type like string.
You should also probably not use the namespace System.Workspace, but something related to your own project.
After your response, the only thing I can guess that the BasePar object is intended for, is to be used within a DataTemplate, on an ItemsControl say. DataTemplates have the behaviour that when they do not know how to render an Object they will fall back the the Object's .ToString() method.
Now, in my comment I said that I don't think the TextBox can have a DataTemplate, and I believe this is true however I did find a trick at this Stackoverflow question which templates a content control and a textblock instead. The code is below:
<Window x:Class="WpfApplication2.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:c="clr-namespace:System.Workspace"
Title="MainWindow" Height="350" Width="525">
<Grid>
<Grid.Resources>
<c:Parameter x:Key="mySource"/>
<DataTemplate x:Key="MyDataTemplate">
<TextBlock Text="{Binding}"/>
</DataTemplate>
</Grid.Resources>
<Canvas>
<Canvas.DataContext>
<Binding Source="{StaticResource mySource}" />
</Canvas.DataContext>
<ContentControl
Content="{Binding Path=JobKey}"
ContentTemplate="{StaticResource MyDataTemplate}" />
</Canvas>
</Grid>
I don't have time right now to get the TextBox working - don't even know if it is possible, given my first few tries. However, this might help get you where you need to go.
But still - if I was me I'd just use simple binding to standard objects. I can't see the benefit of the BasePar class in this scenario.
What does the BasePar implementation look like? Have a look in the Debug Output window to see if you have a line like this:
System.Windows.Data Error: 1 : Cannot create default converter to perform 'two-way' conversions between types 'WpfApplication1.BasePar' and 'System.String'. Consider using Converter property of Binding. BindingExpression:Path=JobKey; DataItem='Parameter' (HashCode=14209755); target element is 'TextBox' (Name='TextBox'); target property is 'Text' (type 'String')
This is telling you that you are trying to bind to the property, but WPF cannot create a 2-way binding, because it cannot convert the text (you type into the TextBox) into a 'BasePar' object.
As per David's suggestion, you could bind to a primitive string type, or alternately (as per the warning message above) you could add a Converter to the binding to convert a string into a BasePar.
you need to make jobkey a DependencyProperty by deriving it from DependencyObject or derive your class from INotifyPropertyChanged and add all the notify code, etc.
if you do not do this, then you will not receive update notifications and your bindings wont work as expected.
Path="jobKey"
You need to bind to the property not the field, i.e. make that upper-case. Also: To debug bindings check the Output-window in Visiual Studio.

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