Cannot bind my Converter class in my XAML command that pass parameter - xaml

This is my XAML that is trying to have my ListView pass a parameter to the ViewModel command.
xmlns:mvvm="http://www.galasoft.ch/mvvmlight"
<ListBox x:Name="MyListView" ItemsSource="{Binding Objects}">
<i:Interaction.Triggers>
<i:EventTrigger EventName="SelectionChanged">
<mvvm:EventToCommand Command="{Binding MyCommand}"
PassEventArgsToCommand="True"
EventArgsConverter="{StaticResource ParamConverter }"
EventArgsConverterParameter ="{Binding Name}"/>
</i:EventTrigger>
</i:Interaction.Triggers>
<ListBox.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding Name}"/>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
And this is my converter:
public class ParamConverter : IEventArgsConverter
{
public object Convert(object value, object parameter)
{
var args = (SelectionChangedEventArgs)value;
var name = parameter as string;
return (string)name.ToString();
}
}
But I got the following error:
The resource "ParamConverter" could not be resolved

Your converter is not declared in XAML, you should add something like
<ListBox.Resources>
<yournamespace:ParamConverter x:Key="ParamConverter"/>
</ListBox.Resources>
inside your listbox tags.
EDIT: I'm not an expert at all, so bear with my "imprecise" terms if any. I think you're missing something: there is no magic that allows your XAML to be aware of your C#. You need to tell XAML that somewhere in your code (in yournamespace) there will be a ParamConverter object, that can be referenced inside xaml with ParamConverter key.
You can declare your resource locally inside ListBox tags as suggested, or at outer scope if needed.
Once resource is declared inside XAML, you can access it via StaticResource.

Related

Use ViewLocator inside TabControl.ContentTemplate

In an AvaloniaUI window, I want to have a TabControl whose tabs are added and removed from an ObservableCollection<T>. The tab's "title" (the text appearing on the tab strip) should be set inside each item of the collection, which could belong to a different type.
For that I defined a type:
public abstract class TabViewModelBase : ViewModelBase
{
public abstract string TabHeader { get; }
}
and my collection is defined like this:
public ObservableCollection<TabViewModelBase> OpenTabs { get; } = new();
In the axaml file, this is the definition of the TabControl:
<TabControl Items="{Binding OpenTabs}">
<TabControl.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding TabHeader}"/>
</DataTemplate>
</TabControl.ItemTemplate>
</TabControl>
So far, this works like a charm.
The problem begins when I also want to set up a container for the view inside each tab, which should not be a part of the contained view itself. I've tried by editing the xaml above and setting a ContentTemplate like this:
<TabControl Items="{Binding OpenTabs}">
<TabControl.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding TabHeader}"/>
</DataTemplate>
</TabControl.ItemTemplate>
<TabControl.ContentTemplate>
<DataTemplate>
<Border Child="{Binding}"/>
</DataTemplate>
</TabControl.ContentTemplate>
</TabControl>
However this results in the following error:
[Binding] Error in binding to 'Avalonia.Controls.Border'.'Child': 'Could not convert 'Project.ViewModels.TestingViewModel' to 'IControl'.'
This seems to be because ViewLocator, which automatically matches a view model to a view based on its name, is not being called. I assume this is because I've defined a DataTemplate inside TabControl.ContentTemplate.
Is it possible to instruct Avalonia to use ViewLocator inside TabControl.ContentTemplate, so that a view is selected based on its name?
<Border Child="{Binding}"/>
Border expects an actual control as a child, not a view model. You need to use ContentControl instead. It can also have it's own data template or view locator.
I found a way to work around the issue, by defining an IValueConverter that uses ViewLocator internally:
public class ViewModelValueConverter : IValueConverter
{
public object? Convert(
object value, Type targetType, object parameter, CultureInfo culture
)
{
if (value == null)
return null;
if (
value is ViewModelBase viewModel
&& targetType.IsAssignableFrom(typeof(IControl))
)
{
ViewLocator viewLocator = new();
return viewLocator.Build(value);
}
throw new NotSupportedException();
}
public object ConvertBack(
object value, Type targetType, object parameter, CultureInfo culture
)
{
throw new NotSupportedException();
}
}
and using it in XAML:
<Window.Resources>
<local:ViewModelValueConverter x:Key="variableView"/>
</Window.Resources>
<TabControl Items="{Binding OpenTabs}">
<TabControl.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding TabHeader}"/>
</DataTemplate>
</TabControl.ItemTemplate>
<TabControl.ContentTemplate>
<DataTemplate>
<Border Child="{Binding, Converter={StaticResource variableView}}"/>
</DataTemplate>
</TabControl.ContentTemplate>
</TabControl>
but it feels like there might be a simpler solution.

Cannot bind to button events using x:Bind in DataTemplates - generates XAML error

With the {x:Bind} markup syntax you can bind to events provided the method meets the following requirements:
Match the signature of the event.
OR have no parameters.
OR have the same number of parameters of types that are assignable from the types of the event parameters.
This works perfectly fine outside of a DataTemplate. Once the binding happens inside the DataTemplate the compiler generates the following error:
Xaml Internal Error error WMC9999: Object reference not set to an
instance of an object.
What is the fix for binding to events inside DataTemplates?
Full example code here.
Snippet of the example code below - note the first button (line 2) is fine and the second button (line 6) is also fine. If you comment out line 6 and and comment in line 7, the error occurs.
<StackPanel Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
<Button Tapped="{x:Bind Click}" Content="WORKING"/>
<ListView ItemsSource="{x:Bind Names}">
<ListView.ItemTemplate>
<DataTemplate x:DataType="local:Customer">
<Button Content="{x:Bind Title}"/>
<!--<Button Tapped="{x:Bind Clicky}" Content="{x:Bind Title}"/>-->
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</StackPanel>
I was able to get it to work with the following code:
<DataTemplate x:DataType="local:Customer">
<StackPanel Orientation="Vertical">
<Button Tapped="{x:Bind Clicky}" Content="{x:Bind Title}" />
</StackPanel>
</DataTemplate>
It seems as though you need to have it inside a container for it work. I have no idea why I am guessing magic.
The parser cannot find Clicky from the datacontext of the button while in the template. Because the object that is being handed to the button in the template (from the Names on the ItemSource of the parent) is not the same as outside the template which has a Clicky. You will need to bind Clicky to the page's datacontext to get it to work.
Otherwise turn off any design time operations by setting Tapped="{x:Bind Clicky, IsDesignTimeCreatable=False}.

Get ListBox DataContext from UserControl

I have a UserControl with a button inside it. The UserControl its DataContext is one of my models so I can bind to it. However, for the button I want to be able to call a method from my viewmodel. The DataContext of the ListBox is this ViewModel.
Because my ContextMenu also needs the same DataContext I've bound them like this:
Command="{Binding Path=DataContext.AttendEventCommand, ElementName=EventListBox}"
Calling the EventListBox element and using its DataContext to call the AttendEventCommand. However I would like to call the AttendEventCommand from a button on the UserControl. I tried doing it the same way but sadly it doesn't work.
My data context is set like this:
DataContext="{Binding Path=EventList, Source={StaticResource Locator}}
My listbox code:
<ListBox x:Name="EventListBox" ItemsSource="{Binding Occurrences}" Margin="0,50,0,0" >
<ListBox.ItemTemplate>
<DataTemplate>
<Grid>
<uctl:EventListItem HorizontalAlignment="Stretch" VerticalAlignment="Stretch" Width="auto" Height="auto">
<toolkit:ContextMenuService.ContextMenu>
<toolkit:ContextMenu IsZoomEnabled="True" x:Name="ContextMenu">
<toolkit:MenuItem x:Name="Going" Header="{Binding AttendingText}" Command="{Binding Path=DataContext.AttendEventCommand, ElementName=EventListBox}" CommandParameter="{Binding}"/>
</toolkit:ContextMenu>
</toolkit:ContextMenuService.ContextMenu>
</uctl:EventListItem>
</Grid>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
And my UserControl's button:
<Button Grid.RowSpan="3" Grid.Column="5" Opacity="0" Command="{Binding Path=DataContext.AttendEventCommand, ElementName=EventListBox}" CommandParameter="{Binding}"/>
I believe your problem is not that what you want to do is not working; instead, your design appears to be wrong.
What you have now is like this:
You have a Window that has a DataContext and a ListBox. The ListBox has an ItemsSource, which we'll assume is some IEnumerable<Occurrence>.
The appearance of each item in your ListBox is an EventListItem, which is a UserControl that contains at least one Button.
You want this Button's Command to call a method on your Window's DataContext.
This last sentence is wrong. The fact that the item has the button implies that it does something that is related to the item, not the window contents. If this is not true, then the visual design of the window and listbox items should probably be reconsidered.
If the button is in fact affecting the item, then you should not call a method on your Window's DataContext, but instead call a method on your item's DataContext.
The solution is to wrap your model object Occurrence in a view model class of its own. Let's call it OccurrenceViewModel. Your ListBox's ItemsSource would be some form of IEnumerable<OccurrenceViewModel>. Because it's a view model, it's allowed to implement Command methods, which can then in one way or another manipulate the Occurrence, either directly or preferably by passing it to some class that implements the use case.
The DataContext of your EventListItem will be a Model of your ItemsSource because it is part of the DataTemplate. So you have to set it explicitly.
Refer to How to implement a navigation button for some of the code I'll be using as a solution.
Lets assume your custom UserControlis very basic like so:
<UserControl>
<Grid x:Name="LayoutRoot" Background="{StaticResource PhoneChromeBrush}">
<Button Command="{Binding DataContext.SimpleCommand}" CommandParameter="1"></Button>
</Grid>
</UserControl>
Where SimpleCommand is the Command you want to call in the Top View Model.
Then you have to change your DataTemplate to
<DataTemplate>
<Grid>
<uctl:EventListItem
DataContext="{Binding ElementName=myListBox}"/>
<!-- more xaml -->
</Grid>
</DataTemplate>
Your <toolkit:ContextMenu> should work as is.
Put a break point at the Execute function of the ICommand and you will see it will get
hit there everytime.
public void Execute(object parameter)
{
// logic to execute when user hits the command
int debug_var = 0; // put a break point here
}

Retrieving value from static extension XAML

How do I retrieve the value (Int32.MaxValue) from the static extension:
<x:Static
x:Key="TooltipTimeout"
Member="s:Int32.MaxValue"
/>
...
<blablalba TooltipService.ShowDuration="{StaticResource TooltipTimeout}"/> <-- this does not work by the way
Methinks you're doing something else wrong. Slap this in kaxaml:
<Page
xmlns:sys="clr-namespace:System;assembly=mscorlib"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<Page.Resources>
<x:Static x:Key="Derp" Member="sys:Int32.MaxValue"/>
</Page.Resources>
<Grid>
<TextBlock
ToolTipService.ShowDuration="{StaticResource Derp}"
ToolTip="Derp" Text="Herp" />
</Grid>
</Page>
Mod tested, mother approved.
If I had to guess, I think you're not defining your xml namespace for Int32 correctly.
In WPF, You can access static member directly, like this,
<TextBlock TooltipService.ShowDuration="{x:Static s:Int32.MaxValue}"/>
However, you cannot do the same in Silverlight, as it wouldn't work. In silveright, you've to write a wrapper class, like this,
public class StaticMemberAccess
{
public int Int32Max { get { return Int32.MaxValue; } }
//define other wrapper propeties here, to access static member of .Net or your classes
}
Then do this in XAML,
<UserControl.Resources>
<local:StaticMemberAccess x:Key="SMA"/>
</UserControl.Resources>
<TextBlock TooltipService.ShowDuration="{Binding Source={StaticResource SMA}, Path=Int32Max}"/>
.
Try to bind to your resource by setting it as the Source of your binding:
{Binding Source={StaticResource TooltipTimeout}}

Why can't get validation error display in validationSummary?

I have a form with some validations set in entity metadata class. and then binding entity instance to UI by VM. Something as below:
Xaml like:
<Grid x:Name="LayoutRoot">
<StackPanel VerticalAlignment="Top">
<input:ValidationSummary />
</StackPanel>
<TextBox Text="{Binding Name, Mode=TwoWay}" />
<ComboBox x:Name="xTest" ItemsSource="{Binding MyList}"
SelectedItem="{Binding MyItem,Mode=TwoWay,
DisplayMemberPath="MyName"
ValidatesOnDataErrors=True,
ValidatesOnNotifyDataErrors=True,
ValidatesOnExceptions=True,
NotifyOnValidationError=True,UpdateSourceTrigger=Explicit}" />
</Grid>
Code-behind like:
public MyForm()
{
InitializeComponent();
this.xTest.BindingValidationError +=new EventHandler<ValidationErrorEventArgs>((s,e)=>{
BindingExpression be = this.xTest.GetBindingExpression(ComboBox.SelectedItemProperty);
be.UpdateSource();
if (e.Action == ValidationErrorEventAction.Added)
((ComboBox)s).Foreground = new SolidColorBrush(Colors.Red);
});
}
Metadata like:
[Required]
public string Name { get; set; }
[RequiredAttribute]
public int MyItemID { get; set; }
But when running the app, I got nothing display in valudationSummary.
For CombBox, even there is error, looks like BindingValidationError event is never fired.
How to resolve it?
Why are you using an Explicit UpdateSourceTrigger?
Silverlight validation happens inside the binding framework, when the binding is updating the source object. The way you have this, there won't be a binding validation error because you never tell the binding to update the source object. Well, actually you do, but it happens inside the validation error event handler. You've written chicken-and-egg code.
Remove your UpdateSourceTrigger on your binding or set it to Default.
Remove the explicit call to BindingExpression.UpdateSource.
Remove setting the ComboBox foreground to red - you are using NotifyOnValidationError=True, which eliminates any need to manually color the control.
Remove the DisplayMemberPath from the binding
So your XAML:
<Grid x:Name="LayoutRoot">
<StackPanel VerticalAlignment="Top">
<input:ValidationSummary />
<ComboBox x:Name="xTest" ItemsSource="{Binding MyList}"
SelectedItem="{Binding MyItem,
Mode=TwoWay,
ValidatesOnDataErrors=True,
ValidatesOnNotifyDataErrors=True,
ValidatesOnExceptions=True,
NotifyOnValidationError=True}" />
</StackPanel>
</Grid>
And your code:
public MyForm()
{
InitializeComponent();
// you don't need anything here to have the validations work
}