I need to change some functionality in a WPF app we've written. We use MVVM Light to implement MVVM. Whenever we've needed to pass some parameters to a method we've used MVVM Light's Messenger class. I've got to pass 3 parameters to a method, but I thought I'd try doing this without using the Messenger class, but instead I hoped I could do it using the RelayCommand() method. I did a search and found this post here on SO, from some years ago. But at least to me, I think this won't work as it's using just 1 type; string in this case. After making some trials and realizing that I'd done it wrong, I decided I could probably create a class with the 3 values I need in it as properties of the class, put it into Models folder and use
new RelayCommand<MyClass>()
So, first question, just to verify that I've got the right idea, I think I would do something like this:
new RelayCommand<MyClass>((mc) => MyMethod(mc.Prop_A, mc.Prop_B, mc.Prop_C)
Is that correct?
Assuming the answer to the above is yes, then how do I actually pass parameters to this when I bind to it in the XAML? This command is going to be associated with a button on the window/page, so I'll be using the Button's Command property. How do I actually pass in the values for the MyClass instances Prop_A, Prop_B and Prop_C?
So, first question, just to verify that I've got the right idea, I
think I would do something like this:
new RelayCommand<MyClass>((mc) => MyMethod(mc.Prop_A, mc.Prop_B, mc.Prop_C)
This is correct.
Assuming the answer to the above is yes, then how do I actually pass
parameters to this when I bind to it in the XAML? This command is
going to be associated with a button on the window/page, so I'll be
using the Button's Command property. How do I actually pass in the
values for the MyClass instances Prop_A, Prop_B and Prop_C?
This will actually depend on where would Prop_A, Prop_B and Prop_C come from. If these properties are already inside your view model, then there is no need for you to pass parameters using XAML.
new RelayCommand<MyClass>((mc) => MyMethod(mc.Prop_A, mc.Prop_B, mc.Prop_C)
will change to
new RelayCommand<object>((param) =>
{
// param is not used.
var mc = this.MC; // assuming your view model holds the mc value
MyMethod(mc.Prop_A, mc.Prop_B, mc.Prop_C);
});
We must make sure that when we load our view model, we have everything we need. Else, use an IoC to fetch whatever it is you need to.
Binding a parameter to your command is often useful for something like a calculator app where you want to pass the button value to your command such as 0 - 9.
<Button Grid.Row="0" Grid.Column="1" Content="7" Command="{Binding PerformAction}" CommandParameter="7"/>
I would want to stay away from defining classes in your view. For the separation of concern, the view should only know of the properties to be bounded to and not the models.
So, first question, just to verify that I've got the right idea, I think I would do something like this:
new RelayCommand<MyClass>((mc) => MyMethod(mc.Prop_A, mc.Prop_B, mc.Prop_C)
Is that correct?
Yes, it is.
How do I actually pass in the values for the MyClass instances Prop_A, Prop_B and Prop_C?
Simply create an instance of the class that holds the parameters inside your xaml as command parameter:
<Button Command="{Binding Command}">
<Button.CommandParameter>
<local:MyClass Prop_A="a value" Prop_B="b value" Prop_C="c value" />
</Button.CommandParameter>
</Button>
There is another approach to do this by using IMultiValueConverter:
class MultiValueConverter : IMultiValueConverter
{
public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
{
foreach (var item in values)
{
//process the properties passed in and you will need to unbox those parameters
}
return new object();
}
public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
And then in xaml (Button code):
<Button Content="Test" Style="{StaticResource contextMenuAware}" Command="{Binding MultiParameterCommand}">
<Button.CommandParameter>
<MultiBinding Converter="{StaticResource MultiValueConverter}">
<Binding Path="Items"/>
<!-- Pass more Bindings here or static values -->
</MultiBinding>
</Button.CommandParameter>
</Button>
Here is the code for inclusion of the converter:
xmlns:converter="clr-namespace:SO_app.Converters"
And then in you Window Resources tag:
<converter:MultiValueConverter x:Key="MultiValueConverter"/>
This way you can use Binding when passing parameters without implementing DependencyProperties.
Here is how I did it:
Your CommandRelay object takes object as parameter, you convert that object to object[] then each element to its own object.
private RelayCommand<object> _YourCommand;
public RelayCommand<object> YourCommand
{
get
{
return _YourCommand ?? (_YourCommand = new RelayCommand<object>(p =>
{
var values = (object[]) p;
int item1 = int.Parse(values[0].ToString());
string item2 = values[1].ToString();
double item3 = double.Parse(values[2].ToString());
}));
}
}
Then, in xaml (Of course, your Paths in Binding must be valid references to your binded objects)
<Button Command="{Binding YourCommand}">
<Button.CommandParameter>
<MultiBinding>
<Binding Path="Item1"/>
<Binding Path="Item2"/>
<Binding Path="Item3"/>
</MultiBinding>
</Button.CommandParameter>
</Button>
Related
Is it possible to call a helper function in XAML that takes any number of parameters using x:Bind? I have this XAML code:
<Button Content="Button content"
Margin="0,0,10,0"
Command="{Binding SomeCommand}"
IsEnabled="{x:Bind helpers:CommonHelpers.TrueForAll(ViewModel.Property,ViewModel.SomeOtherProperty)}"
VerticalAlignment="Center">
</Button>
where the TrueForAll function looks like this:
public static bool TrueForAll(params object[] objects) => objects.All(x => x != null);
When trying to use this in action with multiple parameters, the compiler says Cannot find a function overload that takes 2 parameters. and when only using one, it expects object[] so it says Expected argument of type 'Object[]', but found 'MyType'
The behavior is related to the params keyword. x:Bind can't recognize params that you defined. It is still looking for method with explicit parameter lists.
My suggestion is that you might need to use List<object> or ObservableCollection<object> as the parameter for the method. And create such a property in your ViewModel as well. This could be accepted by the x:Bind.
Is it possible to call a helper function in XAML that takes any number of parameters using x:Bind?
No.
The solution is to define the method with explicit parameters:
public static bool TrueForAll(IEnumerable<object> objects)
=> objects?.All(x => x != null) == true;
And create the parameter programmatically:
public IEnumerable<object> Input =>
new object[] { ViewModel.Property, ViewModel.SomeOtherProperty };
XAML is a markup language and trying to do things like creating arrays in it is an anti-pattern really. You should create the input parameter in the code-behind of the very same view or move your logic to the view model.
This question already has answers here:
Binding ConverterParameter
(3 answers)
Closed 4 years ago.
I am trying to bind the text of a textblock based on two things -
Object ShoppingList
Object Items(which is a property of the ShoppingList object. Type is List).
I want to invoke the converter as I want the text to be dependent on change in the value of either of the above.The only way that I could think of was this way as shown below. But this is not possible as I cannot bind the ConverterParameter to the object ShoppingList as it is not a dependency property .
<TextBlock
Margin="5"
TextWrapping="Wrap"
Text="{Binding Items, Converter={StaticResource ABCDConverter}, ConverterParameter="???" />
Below is the converter I had written
Convert(Items obj, object par, xyz culture)
{
if (obj != null && par!=null)
{
var parameter = (ShoppingList)par;
// Different Logic to determine the string to be returned
}
return string.Empty;
}
In simple words, how can I invoke the converter based on changes in either of Items or ShoppingList
Sounds like you're looking for MultiBinding, paired with an IMultiValueConverter.
That being said, I would strongly suggest that you determine the needed value in your ViewModel since you already have all the needed properties there and you know when and how they change. Once you have your derived property, just use regular binding to bind to it in the View. Using MultiBindings will generally tend to break your separation of concerns as you will end up adding specific logic to the converter that really should be in the ViewModel. One case where I did find MultiBindings indispensable was in a group header template (i.e. for a DataGrid). It would be pretty well impossible to get the values from the ViewModel as you don't know how many groups you have or what they will contain at runtime as there are just too many moving parts. In this case, MultiBindings were great.
On the other hand, if you are just targeting a specific element that you know about at design time, you should generally avoid using MultiBinding for the reasons stated above. In addition, MutliBinding are quite verbose compared to regular Bindings, making your XAML harder to read which creates a greater potential for bugs and limits future extensibility and maintainability.
But if you must, here's a simple example:
XAML
<Window x:Class="testapp.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:testapp"
Title="MainWindow" Height="350" Width="525">
<Window.Resources>
<local:MyMultiConverter x:Key="multiTextConverter"/>
</Window.Resources>
<Grid>
<TextBlock>
<TextBlock.Text>
<MultiBinding Converter="{StaticResource multiTextConverter}">
<Binding Path="someProp"/>
<Binding Path="someOtherProp" />
</MultiBinding>
</TextBlock.Text>
</TextBlock>
</Grid>
</Window>
Converter
public class MyMultiConverter : IMultiValueConverter
{
public object Convert(object[] values, Type targetType,
object parameter, CultureInfo culture)
{
string ret = null;
if(values.Count() > 1)
{
string value1 = values[0] as string;
string value2 = values[1] as string;
ret = value1 + value2;
}
return ret;
}
public object[] ConvertBack(object value, Type[] targetTypes,
object parameter, CultureInfo culture)
{
}
}
Now, if you're binding to a List, and, assuming you care when items are added or removed, you will rather need to use an ObservableCollection as it implements the INotifyCollectionChanged Interface see here.But this is not quite enough, as the binding will not be subscribing to that event. You will need to listen to the change in collection in your DataContext (ViewModel?). Then create some dummy property, and when the collection changes, just increment the dummy property (with INotifyPropertyChanged of course) and use that property in the multibinding as a third binding. This way, the TextBlock text will get updated if either a property changes, or your list changes.
If you don't care about the changes in the collection, only when you assign a whole new collection, then the sample provided will work as is.
I'd like to be able to display an index value from within a DataTemplate, but I don't want the data to be persisted or backed by the model or viewmodel. In other words, if the order of the items in the OC changes, I don't want to have to recalculate the indexes. The value should be intrinsically tied to the underlying index in the OC. It is okay if the index is 0-based (in fact, I'd expect it).
One method that others have used is the AlternationIndex AP, but this has its own pitfalls for certain situations.
One last thought: I can't help but think that a converter is going to be helpful in a final solution.
I would use a converter to do this.
The trick is giving it the source collection, either on the ConverterParameter or a Dependency Property. At that point, conversion is as simple as using IndexOf.
Here's a sample converter that does this:
public class ItemToIndexConverter : IValueConverter
{
public object Convert(...)
{
CollectionViewSource itemSource = parameter as CollectionViewSource;
IEnumerable<object> items = itemSource.Source as IEnumerable<object>;
return items.IndexOf(value as object);
}
public object ConvertBack(...)
{
return Binding.DoNothing;
}
}
You can make the implementation strongly typed, return a formatted string as a number, etc. The basic pattern will be as above though.
This implementation uses the parameter approach, as making a DP is more messy in my view. Because you can't bind ConverterParameter, I have it set to a static resource that is bound to the collection:
<CollectionViewSource x:Key="collectionSource" Source="{Binding Path=MyCollection}" />
...
<TextBlock Text="{Binding Converter={StaticResource ResourceKey=ItemToIndexConverter},
ConverterParameter={StaticResource ResourceKey=collectionSource}}"/>
I am building an application that can be used by many users. Each user is classified to one of the next Authentication levels:
public enum AuthenticationEnum
{
User,
Technitian,
Administrator,
Developer
}
Some controls (such as buttons) are exposed only to certain levels of users.
I have a property that holds the authentication level of the current user:
public AuthenticationEnum CurrentAuthenticationLevel { get; set; }
I want to bind this property to the 'Visibilty' property of some controls and pass a parameter to the Converter method, telling it what is the lowest authentication level that is able to see the control.
For example:
<Button Visibility="{Binding Path=CurrentAuthenticationLevel, Converter={StaticResource AuthenticationToVisibility}, ConverterParameter="Administrator"}"/>
means that only 'Administrator' and 'Developer' can see the button.
Unfortunately, the above code passes "Administrator" as a string. Of course I can use switch/case inside the converter method and convert the string to AuthenticationEnum. But this is ugly and prone to maintenance errors (each time the enum changes - the converter method would require a change also).
Is there a better way to pass a nontrivial object as a parameter?
ArsenMkrt's answer is correct,
Another way of doing this is to use the x:Static syntax in the ConverterParameter
<Button ...
Visibility="{Binding Path=CurrentAuthenticationLevel,
Converter={StaticResource AuthenticationToVisibility},
ConverterParameter={x:Static local:AuthenticationEnum.Administrator}}"/>
And in the converter
public class AuthenticationToVisibility : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
AuthenticationEnum authenticationEnum = (AuthenticationEnum)parameter;
//...
}
}
User
(AuthenticationEnum)Enum.Parse(typeof(AuthenticationEnum),parameter)
to parse string as enumerator
In my application I have
<Rectangle.Margin>
<MultiBinding Converter="{StaticResource XYPosToThicknessConverter}">
<Binding Path="XPos"/>
<Binding Path="YPos"/>
</MultiBinding>
</Rectangle.Margin>
The Data Context is set during runtime. The application works, but the design window in VS does not show a preview but System.InvalidCastException. That’s why I added a default object in the XYPosToThicknessConverter which is ugly.
class XYPosToThicknessConverter : IMultiValueConverter
{
public object Convert(object[] values, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
// stupid check to give the design window its default object.
if (!(values[0] is IConvertible))
return new System.Windows.Thickness(3, 3, 0, 0);
// useful code and exception throwing starts here
// ...
}
}
My Questions:
What does VS/the process that builds the design window pass to XYPosToThicknessConverter and what is way to find it out by myself.
How do I change my XAML code, so that the design window gets its default object and is this the best way to handle this problem?
I’m using VS2010RC with Net4.0
Try put a fallback value to your binding. That's what I do to get stuff to display 'as if' in the design mode.
Something="{Binding Smthing, FallbackValue='hello world'}"
HTH
You'll need to make sure that the designer can get a valid copy of "XPos" and "YPos", and they are the same values as at runtime.
Chances are your DataContext is not being set in the View appropriately, so the converter gets null. If you set the DataContext to a valid object (which can be design time data), you're code should work without the defaults in the converter.