I have a new UserControl backed by UserControl01.cs that is exposing two properties. One is a plain old CLR property, the other the newer DP property format.
eg:
string PropertyOne {get;set;}
and the second property is a public DP (construct is too long to list here).
From the XAML side, I wish to expose these value. How can I do that?
On both properties (old CLR as well as second DP wrapper format) I've tried syntax like:
<TextBlock Text={Binding Prop1}/>
<TextBlock Text={Binding Source=., Path=Prop1}/>
I've tried putting a ref to the class type in the Resource dictionary and referencing it with
<TextBlock Text={Binding Source={StaticReference myType}, Path=Prop1}/>
but that obviously ends up being a stack overflow as the dictionary instantiates a second copy of the Control.
I read a post somewhere that in WPF one can x:Name the control itself, and then
<TextBlock Text="{Binding {ElementName=theName, Path=Prop1}"/>
but we don't have ElementName binding in Ag, so that's not the way.
How can I bind to the UserControl's property? Any property!
If that's not possible, and you can only bind to DTO's or other BO's, what's the guiding logic/explanation as to how we should design UserControls that want to expose their values?
Silverlight 3 has control to control binding.
http://silverlight.net/learn/learnvideo.aspx?video=187309
Related
i already the project from the official tutorial of .NET MAUI until step 5 using Communitytoolkit.Mvvm:
text
Now, instead of binding only a Text (which is a standard type that can be accessed from everywhere) i would like to bind a simple object (called ItemGroup) with two members (bool isChecked and string name).
How to do that?
For a global access i made this class in the MainView folder called ItemGroup. This class is not accessable and i don't know how to do that it is.
I changed the code in the MainPage.xaml like this:
<CollectionView ItemsSource="{Binding Items}"
Grid.Row="1">
<CollectionView.ItemTemplate>
<DataTemplate x:DataType="{x:Type x:ViewModel.ItemGroup}">
<Grid >
<CheckBox IsChecked="{Binding ItemGroup.IsChecked}" Grid.Column="0"/>
<Label Text="{Binding ItemGroup.name}" Padding="10" Grid.Column="1"
BackgroundColor="LightGray"/>
</Grid>
</DataTemplate>
</CollectionView.ItemTemplate>
</CollectionView>
See also the project structure with the ItemGroup class in the ViewModel folder as well as the error message:
where the content page is declared as this:
Remark: The MainViewModel looks like this:
Should i declare some uses, or namespace?
where in the project should i place the Class of the objects i would bind?
Thanks in advance, Thomas
Also tryed to implement the class ItemGroup in the MainViewModel.cs but then i had any more problems with access to this class.
Try this
<Label Text="{Binding name}" …
Note that name must be a public property
You have a number of issues here.
The community mvvm toolkit includes code generators.
A variable:
[ObservableProperty]
string text;
Is examined by the code generator at compile time and in a partial class it will add a public property Text.
Binding is case sensitive and you need to bind to public properties so you need to use upper case on that first letter. Binding Text rather than Binding text.
You might have other instances where you did the same sort of thing.
I don't see where you use it but that add [Relaycommand] will generate AddCommand as a public property which you bind to.
Additionally you have misunderstood how an itemscontrol gets an item out a bound collection per row. As DevenCC points out, once you bind ItemsSource to Items then each row will get an instance of whatever is in that collection so you should bind IsChecked rather than ParentProperty.IsChecked.
As to where to put classes. In large apps it is a nuisance to flip between a folder contains views and another contains viewmodels. You might want to consider a folder contains each pair of view and viewmodel. Hence a foo folder containing fooView and fooViewModel
I believe your problem lies with you Binding declaration inside you ItemTemplate. Given that you bound your CollectionView's ItemSource to "items", the ItemTemplate's data context is now a single itemGroup from your list. Therefore, you should not be writing
<CheckBox IsChecked="{Binding ItemGroup.IsChecked}"[...]
But instead
<CheckBox IsChecked="{Binding isChecked}"[...]
Since you are already "within" a single itemgroup object. Same goes for your Label. Furthermore, I don't think you actually need to declare the Datatype for your item's DataTemplate.
p.s. Watch out for your item declaration, it seems like you have both items and Items declared in your ViewModel; and both seem public.
I need help with a change of perspective.
I got stuck trying to approach UWP in a way I used to do in WPF regarding a MVVM pattern for managing UserControls dynamically.
I naturally tried to perform the same pattern in UWP but got stuck on various things like UWP not supporting 'x:Type' ...
Situation is; time to rethink this approach and look for a new direction. Seems I'm forced to abandon to use implicit binding in a similar fashion to the WPF pattern, using the Content property of a ContentPresenter and a VM property 'of type Object', which maintain a selected ViewModel. It was a simple and clean approach for matching up the correct View automagically with the VM set in ActiveViewModel.
the below was such a simple way of managing many views all over the place, odd MS not fixing this? But, back to the big Q: what now in UWP!?
<ContentPresenter Content="{Binding ActiveViewModel}">
<ContentPresenter.Resources>
<DataTemplate DataType="{x:Type local:OneViewModel}">
<local:OneView />
</DataTemplate>
<DataTemplate DataType="{x:Type local:TwoViewModel}">
<local:TwoView />
</DataTemplate>
</ContentPresenter.Resources>
</ContentPresenter>
What Shall I do instead of this!? Anyone found a new efficient way of doing it? I got stuck in my stubborn mind and need someone to kick my butt so I go forward. Getting to old to change, but due to this profession it seems I constantly have to. :)
Looking at the DataTemplate documentation, there's a paragraph explaining the situation which you are trying to figure out.
For advanced data binding scenarios, you might want to have properties
of the data determine which template should produce their UI
representations. For this scenario, you can use a DataTemplateSelector
and set properties such as ItemTemplateSelector to assign it to a data
view. A DataTemplateSelector is a logic class you write yourself,
which has a method that returns exactly one DataTemplate to the
binding engine based on your own logic interacting with your data. For
more info, see Data binding in depth.
Here, you have an example on how you can select distinct DataTemplate for items in a control such as a ListView based on defined conditions.
Your situation is a bit different from the one described above, but the solution should be within what is explained above.
Create a class which derives from DataTemplateSelector, and override the SelectTemplateCore methods exposed by it, where you define the logic of what DataTemplate should be selected for the specific presented object.
This Derived class should expose properties of type DataTemplate, which identify each single DataTemplate template object, you pretend to be able to choose from.
Just as in the example, you are probably better of by defining the DataTemplate resources on an higher level object, such as the Page itself.
Instantiate your DataTemplateSelector Derived class in XAML as a resource and set each of the properties exposed above of type DataTemplate to the analogous DataTemplate static resource.
Utilize the ContentTemplateSelector dependency property, by setting it your custom DataTemplateSelector.
With this logic, it should be possible to have your ContentPresenter decide correctly between which DataTemplate it should choose from, based on your required UI logic.
Example:
<DataTemplate x:DataType="FooEntity">
<Grid Background="{x:Bind MyClass.MyStaticBindingMethod(???)}" />
</DataTemplate>
It’s easy enough to pass in properties of the entity, but I can’t see a way to pass in the instance itself. Is this feature not supported? I could store a reference to this in FooEntity with a property called Instance (for example), and then go MyClass.MyStaticBindingMethod(Instance), but just want to make sure there isn't a cleaner way.
Relevant docs: https://learn.microsoft.com/en-us/windows/uwp/xaml-platform/x-bind-markup-extension
You cannot pass the instance itself onto a DataTemplate.
The DataTemplate is only responsible for describing the visual structure of a data object and therefore its not part of its job to hold a explicit reference to any CLR object.
DataTemplate is defined to extend the visual structure of data objects, such as GridView/ListView, and those already handle the possibility of referencing to Collections, by setting the ItemsSource dependency property. Taking advantage of this, the DataTemplate simply exposes the customization of your visual structure. However this visual structure should be followed with the necessary bindings, to achieve your desired custom behavior.
If you are dealing with x:Bind, you will have to set the x:DataType, to the type of the Collection which you are setting as the Control ItemsSource, because the compiler needs that information at compile-time.
That is not a problem for Binding because those are evaluated at runtime, with the help of reflection.
I am not sure if I understand correctly, but to bind this, meaning the entity directly, you can just use empty binding:
Background="{x:Bind}"
or
Background="{Binding}"
This however means that FooEntity should derive from Brush so that it is compatible with Background type.
When using traditional {Binding} syntax you could specify element name to point to a specific control on the page, and be able to access its properties. For example if the page is named page you could do:
{Binding ElementName=Page, Path=Name}
With the {x:Bind} syntax it says
With x:Bind, you do not need to use ElementName=xxx as part of the
binding expression. With x:Bind, you can use the name of the element
as the first part of the path for the binding because named elements
become fields within the page or user control that represents the root
binding source.
So for the example above in {x:Bind} would be
{x:Bind page.Name}
Which works fine, until it is inside a data template (for example a ListView's ItemTemplate). In which case it no longer works as it is looking for Page on the data type specified which leads to the following error (assuming my data type is customer):
XamlCompiler error WMC1110: Invalid binding path 'Page.Name' :
Property 'Page' can't be found on type 'Customer'
What is the solution to use {x:Bind} syntax with datatemplates and access controls outside the data template?
Example code is available here (note specific commit)
As far as I know at this point in time there is no way to directly bind to a property of a control using the x:bind method as it does not support the element name inside of its binding definition.
That does not mean you cant bind to a control inside a dataTemplate you can still do something like this to access controls but you just aren't able to use the compiled binding x:Bind syntax.
<DataTemplate x:DataType="local:Customer">
<StackPanel Orientation="Vertical">
<Button Content="{Binding Name, ElementName=page}" />
<TextBlock Text="{x:Bind Title}" />
</StackPanel>
</DataTemplate>
The reason for the error you are getting is due to the way data templates parent their datasource. The x:Bind binding cannot reference a control object and your Customer type does Page.Name property or path. As shown above the only real way of accessing user control properties outside of your control only using XAML is to resort back to the standard binding mechanism.
I hope this answers your question.
In Windows Phone xaml page, some element has x:Name
<TextBlock x:Name="PageTitle" Text="simple" Margin="9,-7,0,0" Style="{StaticResource PhoneTextTitle1Style}"/>
While others have Name
<TextBlock Name="tbSource" Height="30" HorizontalAlignment="Left" Margin="129,178,0,0" Text="Source" VerticalAlignment="Top" Width="304" />
What is the difference ?
The x: part is a namespace alias. It tells the compiler where the property exists. In this case it's pointing to the default namespace for XAML.
The Name property is part of System.Object which is in that namespace.
When you include x:Name to identify a property called Name in XAML what you're explicitly saying is that you're referring to the Name property of the underlying System.Object. As all objects inherit from this it's accessible to all classes.
Why might any of this matter?
If you overrode the Name property in a class then specifying the namespace will allow you to be explicit about which version of Name you're referring to.
Side note: you will save yourself a lot of pain by never overriding Name.
Does it matter which you use?
No. As long as Name is never overridden and you need to refer to the specific version of it.
It's probably in your interest to be consistent in whether you use it or not. Most people do (as does VS when it creates controls for you) so it's probably easiest to keep them there.
Not sure, but I think x:Name elements are accessible in code by their name. e.g. PageTitle.Text = "some text". And "Name" is just a regular property of an element. Please also see the following article about x:Name directive.