XmlnsDefinitionAttribute combined with x:Name causes compilation error with code generation - xaml

I have and issue with using the XmlnsDefinition attribute within a silverlight 4 assembly.
Here's the test case:
In AssemblyInfo.cs of the silverlight project I add the following:
[assembly: XmlnsDefinition("urn:foo", "SilverlightApplication1")]
[assembly: XmlnsDefinition("urn:foo", "SilverlightApplication1.SomeNamespace")]
I edit MainPage.xaml.cs and to make it look like so:
namespace SilverlightApplication1
{
public partial class MainPage : UserControl
{
public MainPage()
{
InitializeComponent();
}
}
}
namespace SilverlightApplication1.SomeNamespace
{
public class SomeControl : ContentControl
{
}
}
Now in MainPage.xaml I have the following:
<UserControl x:Class="SilverlightApplication1.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:foo="urn:foo">
<Grid>
<foo:SomeControl>
<TextBlock Text="Hello World"/>
</foo:SomeControl>
</Grid>
</UserControl>
This compiles and runs fine. The problem occurs when I add the x:Name attribute to the SomeControl tag.
This does not compile:
<foo:SomeControl x:Name="bar">
<TextBlock Text="Hello World"/>
</foo:SomeControl>
Looking at the .g.i.cs file that gets generated, the control is declared as
internal SomeControl bar;
The file is missing either the using statement or the full type name. I've also tried this in WPF and the results are the same. Can anyone tell me what, if anything, I'm doing wrong?

I have the same issue. Based on my searching, it looks like this is not currently supported.
http://forums.silverlight.net/forums/t/84877.aspx
http://social.msdn.microsoft.com/Forums/en-US/wpf/thread/7e7a032a-dad3-4e02-9e5a-d73e346b75ed/

Related

xamarin datatemplateselector: not valid XAML name

I'm trying to do a very common usage of Xamarin.Forms ListView, where I have multiple types of items.
I'm using a DataTemplateSelector and defining the different (two at this point) views in my XAML file. That requires referencing the c# code from the XAML code through a namesspace definition. And, that's where I'm stuck.
The error I'm getting is
XFC0000 Cannot resolve type "local:NodeTemplateSelector".
Here is my XAML, condensed:
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
...
xmlns:local="clr-namespace:varlist">
<ContentPage.Resources>
<ResourceDictionary>
<DataTemplate x:Key="NoteItem">
...
</DataTemplate>
<local:NodeTemplateSelector x:Key="NodeTemplateKey">
NoteTemplate = "{StaticResource NoteItem}"
ImageTemplate = "{StaticResource ImageItem}"
</local:NodeTemplateSelector>
</ResourceDictionary>
</ContentPage.Resources>
</ContentPage>
And, here is C#, also condensed:
namespace varlist
{
[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class ListViewPage : ContentPage
{
...
public class NodeTemplateSelector : DataTemplateSelector
{
public DataTemplate NoteTemplate { get; set; }
public DataTemplate ImageTemplate { get; set; }
protected override DataTemplate OnSelectTemplate (object item, BindableObject container)
{
ListView list = (ListView)container;
if (item is NoteData)
return NoteTemplate;
else // item is ImageData
return ImageTemplate;
}
}
}
}
What do I need to change to get the XAML to recognize NodeTemplateSelector ?
As Jason and Shaw suggested, the NodeTemplateSelector must be in top level class.
Also, another problem I ran into is the syntax in the DataTemplate XAML file. Might as well add this note, in case anyone else has the same trouble:
The NodeTemplateSelector in XAML must be defined as direct content; must be like this:
<local:NodeTemplateSelector
x:Key="NodeTemplate"
NoteItemTemplate="{StaticResource NoteTemplate}"
ImageItemTemplate="{StaticResource ImageTemplate}"
/>
Otherwise you get a rather undecipherable runtime error.

DataBinding and Incomplete Microsoft Documentation

Basically, I'm working through the Microsoft tutorial on WPF:
https://learn.microsoft.com/en-us/dotnet/opbuildpdf/framework/wpf/data/toc.pdf?branch=live
I get to page 8, and (in my opinion) Microsoft screwed up. They don't give any C# code-behind that is necessary to run the following XAML:
<DockPanel
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:c="clr-namespace:SDKSample">
<DockPanel.Resources>
<c:MyData x:Key="myDataSource"/>
</DockPanel.Resources>
<DockPanel.DataContext>
<Binding Source="{StaticResource myDataSource}"/>
</DockPanel.DataContext>
<Button Background="{Binding Path=ColorName}" Width="150" Height="30">
I am bound to be RED!</Button>
</DockPanel>
I follow their description as best as possible, but all I get is this following error message.
The name "MyData" does not exist in the namespace "clr-namespace:SDKSample".
I do what I'm supposed to do: create a c# file, using "Add New Item" and build it, but still that error code pops up again. To save people from having to look up the documentation, here's what they ask for:
Consider the following example, in which the binding source object is
a class named MyData that is defined in the SDKSample namespace. For
demonstration purposes, MyData class has a string property named
ColorName, of which the value is set to "Red". Thus, this example
generates a button with a red background.
I've looked in the various SDK's for this example, hoping I'd find the mysterious C# file somewhere, but alas I can't find it. It seems like Microsoft forgot a link. You know, even if it is somewhere in an SDK, it is extremely hard to find. As someone in a learning-mode, I'd hope that all the gritty details would be provided in the documentation, not just the quote from above, which doesn't go into any details as to where to put the C# file, how you are supposed to build so it will properly get registered as existing.
So, if anyone can find a nice description as to how to get the XAML code to work, by creating a C# class named "MyData" in a "SDKSamples" namespace, I'd be very appreciative.
the xaml works when you add the following:
namespace SDKSample
{
public class MyData
{
public Brush ColorName { get; set; } = Brushes.Red;
}
}
<Window x:Class="StackExchangeQuestion.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:StackExchangeQuestion"
mc:Ignorable="d"
xmlns:c="clr-namespace:SDKSample"
Title="MainWindow" Height="350" Width="525">
<DockPanel >
<DockPanel.Resources>
<c:MyData x:Key="myDataSource"/>
</DockPanel.Resources>
<DockPanel.DataContext>
<Binding Source="{StaticResource myDataSource}"/>
</DockPanel.DataContext>
<Button Background="{Binding Path=ColorName}" Width="150" Height="30">
I am bound to be RED!</Button>
</DockPanel>
</Window>
I'd like to add that Microsoft assumes that you have all the stuff between <Window x:Class and Width="525"> already there. It's kind of sloppy work to just leave out that massive detail in their documentation. Thanks to Milan for getting me to look at what should go inside the <Window>...</Window> part of the code.
Also, in the interest of completeness, the C# code:
using System.Windows;
using System.Windows.Media;
namespace StackExchangeQuestion
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
}
}
namespace SDKSample
{
public class MyData
{
public Brush ColorName { get; set; } = Brushes.Red;
}
}

System.Type as property of converter - only works with unused property in code behind

I have a IValueConverter that has a System.Type property which is set in XAML.
Converter:
internal class EnumTypeConverter : IValueConverter
{
public Type TypeToDisplay { get; set; }
public object Convert(object value, Type targetType, object parameter, string language)
{
return TypeToDisplay?.FullName;
}
public object ConvertBack(object value, Type targetType, object parameter, string language)
{
throw new NotImplementedException();
}
}
XAML:
<Page
x:Class="UWPSystemTypeConverterTest.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:converter="using:UWPSystemTypeConverterTest.Converter"
xmlns:enums="using:UWPSystemTypeConverterTest.Enum"
mc:Ignorable="d">
<Page.Resources>
<converter:EnumTypeConverter x:Key="Converter" TypeToDisplay="enums:CustomEnum" />
</Page.Resources>
<Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
<TextBlock Text="{Binding Converter={StaticResource Converter}}" />
</Grid>
</Page>
When I run the application, I get following error:
Windows.UI.Xaml.Markup.XamlParseException: 'The text associated with
this error code could not be found.
Failed to create a
'UWPSystemTypeConverterTest.Converter.EnumTypeConverter' from the text
'enums:CustomEnum'. [Line: 14 Position: 56]'
If I add a property of type CustomEnum to the code- behind file, which is never used, the application works.
the changed code- behind- File:
public sealed partial class MainPage : Page
{
public CustomEnum WithThisPropertyTheAppWorks { get; set; }
public MainPage()
{
InitializeComponent();
this.DataContext = this;
}
}
The complete project for reproduction is here: https://github.com/SabotageAndi/UWPSystemTypeConverterTest
Line to uncomment is https://github.com/SabotageAndi/UWPSystemTypeConverterTest/blob/master/UWPSystemTypeConverterTest/MainPage.xaml.cs#L13
I suspect that an optimiser of UWP is causing this problem.
Is this really the case?
How can I fix the error without the unused property in the code-behind file?
Targeting UWP Build 10240, a viable work around is to add a dummy instance of the targeted enum in static resources of the page before instantiating the converter.
<Page.Resources>
<enums:CustomEnum x:Key="WorkAround">CustomEnumValue</enums:CustomEnum>
<converter:EnumTypeConverter x:Key="Converter" TypeToDisplay="enums:CustomEnum" />
</Page.Resources>
Info from a MSFT employee on a MVP mailing list:
This behaviour is a current limitation of UWP.
The XAML compiler and the runtime don't support System.Type- typed properties. So the needed metadata is not generated and the runtime can not convert the string to the type.
But because of the public properties on the code-behind, the compiler generates the needed metadata now. I am not that happy with the work around, but it is better than other solutions (e.g. a string property with the fullname to the type).

Property can't be found on ViewModel in UWP app

An Order form in UWP using Template 10 adds products to an order. The error is
Invalid binding path 'OrderViewModel.FindProduct_TextChanged' : Property 'OrderViewModel' can't be found on type 'ProductViewModel'
The relevant xaml snippet is
<Page.DataContext>
<ViewModels:MainPageViewModel x:Name="OrderViewModel" />
</Page.DataContext>
<GridView ItemsSource="{x:Bind OrderViewModel.Products, Mode=TwoWay}">
<GridView.ItemTemplate>
<DataTemplate x:DataType="ViewModels:ProductViewModel" >
<AutoSuggestBox
Name="ProductAutoSuggestBox"
TextMemberPath="{x:Bind ItemCode, Mode=TwoWay}"
TextChanged="{x:Bind OrderViewModel.FindProduct_TextChanged}">
</AutoSuggestBox>
</DataTemplate>
</GridView.ItemTemplate>
</GridView>
The relevant snippet from the OrderViewModel and the ProductViewModel
namespace ViewModels
{
public class OrderViewModel : ViewModelBase
{
public ObservableCollection<Product> Products { get; set; } = new ObservableCollection<Product>();
public void FindProduct_TextChanged(AutoSuggestBox sender, AutoSuggestBoxTextChangedEventArgs args)
{ ... }
}
public class ProductViewModel : ViewModelBase
{
string _ItemCode = default(string);
public string ItemCode { get { return _ItemCode; } set { Set(ref _ItemCode, value); } }
public ProductViewModel()
{
}
}
}
How to I correctly reference FindProduct_TextChanged on the OrderViewModel from the DataTemplate for the GridView which references ProductViewModel?
Voted up to #tao's comment. #Vague, I think you may misunderstand what x:DataType is used for. You can refer to the "DataTemplate and x:DataType" part of Data binding in depth:
When using {x:Bind} in a data template, so that its bindings can be validated (and efficient code generated for them) at compile-time, the DataTemplate needs to declare the type of its data object using x:DataType.
For your scenario, from your code public ObservableCollection<Product> Products { get; set; } = new ObservableCollection<Product>();, the type of your DataTemplate's data object should be your Product class, not your ProductViewModel, and in the meanwhile, your FindProduct_TextChanged event must be find in this Product class, that means your code of FindProduct_TextChanged should be placed in your Product data model.
By the way, I think there is no need to use TwoWay binding for ItemsSource. For this scenario, the binding target is ItemsSource of GridView, the binding source is ObservableCollection<Product> Products, I understand you want to update GridView when your collection is updated, this is work is done with ObservableCollection. Besides, only the binding source here can be changed to notify the binding target, so OneWay binding is enough. But it's not a big problem with your code.
So for your GridView, it should be something like this:
<GridView ItemsSource="{x:Bind OrderViewModel.Products, Mode=OneWay}">
<GridView.ItemTemplate>
<DataTemplate x:DataType="Models:Product" >
<AutoSuggestBox
Name="ProductAutoSuggestBox"
TextMemberPath="{x:Bind ItemCode, Mode=TwoWay}"
TextChanged="{x:Bind FindProduct_TextChanged}">
</AutoSuggestBox>
</DataTemplate>
</GridView.ItemTemplate>
</GridView>
if error is kind of like this I approved its a charset support bug:
Error Invalid binding path 'XX.YY' : Property 'ZZ' can't be found on type 'CCC'
Either xaml and C# supports unicode;
its because you use a non-ascii character in class properties. this is a bug I found today. Just rename your class proprty characters to ascii standards. Hope it will be fixed.

Page with type parameter

I would like to use new feature of UWP -> x:Bind. In order to that, all my pages need to have ViewModel property (as described in tutorials).
To avoid code duplicity, I have established base class as follows:
public abstract class BasePage<TBaseVM> : Page, where TBaseVM : BaseVM
{
public TBaseVM VM { get; private set; }
protected BasePage()
{
DataContextChanged += (s, e) => VM = e.NewValue as TBaseVM;
}
}
As you can see this BasePage class contains property called "VM" and property is of type BaseVM. Hence, I don't need to define VM property on each derived class.
Then I created derived page 'MainPage' defined in xaml as follows:
<pages:BasePage
x:Class="Realarm.View.Pages.MainPage"
x:TypeArguments="viewModel:MainVM">
By doing that, even Resharper's Intellisense offers me properties from "MainVM" in MainPage.xaml, thus is can write:
<ListView ItemsSource="{x:Bind VM.AlarmsVM}">
Unfortunately, when I try to build the project, I get error in MainPage.g.i.cs:
Severity Code Description Project File Line
Error CS0305 Using the generic type 'BasePage' requires 1 type arguments Realarm D:...\Realarm\obj\x86\Debug\View\Pages\MainPage.g.i.cs 13
Any help?
I got this working using Xamarin.Forms.
Base Page:
public abstract class BaseContentPage<TViewModel> : ContentPage where TViewModel : BaseViewModel, new()
HomePage.cs:
public partial class HomePage : BaseContentPage<HomeViewModel>
HomePage.xaml:
<d:BaseContentPage
xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:d="clr-namespace:Sample.Pages;assembly=Sample"
xmlns:vm="clr-namespace:Sample.ViewModels;assembly=Sample"
x:Class="Sample.Pages.HomePage"
x:TypeArguments="vm:HomeViewModel">
<ContentPage.Content>
</ContentPage.Content>
</d:BaseContentPage>
Just add a x:TypeArguments definition at the top of the XAML:
<v:BasePage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:v="clr-namespace:YourApp.Views"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:d="http://xamarin.com/schemas/2014/forms/design"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:vm="clr-namespace:YourApp.ViewModels"
mc:Ignorable="d"
x:TypeArguments="vm:HomeViewModel"
x:Class="YourApp.MainPage">
Worked for me as well when I set the BindingContext as given below in Base Page's constructor:
public BasePage()
{
BindingContext = new TBaseVM();
}