WPF - How to bind to a Dependency Property of custom class - data-binding

I'm once again in WPF binding hell :) I have a public class (Treatment) as follows:
public class Treatment()
{
...
public Ticker SoakTimeActual;
...
}
Within Ticker is a Dependency Property:
public class Ticker : FrameworkElement
{
// Value as string
public static readonly DependencyProperty DisplayIntervalProperty = DependencyProperty.Register("DisplayInterval", typeof(string), typeof(Ticker), null);
public string DisplayInterval
{
get { return (string)GetValue(DisplayIntervalProperty); }
set { SetValue(DisplayIntervalProperty, value); }
}
...
}
In my app, a single Treatment object is created and is meant to be easily accessible in XAML (in app.xaml ):
<Application.Resources>
<ResourceDictionary>
<u:Treatment
x:Key="currentTreatment" />
</ResourceDictionary>
</Application.Resources>
Now, I need to bind to the DisplayInterval dependency property of SoakTimeActual to display this text in its current state. Here is my attempt, which doesn't work:
<TextBlock
Text="{Binding Source={StaticResource currentTreatment}, Path=SoakTimeActual.DisplayInterval}"/>
This, of course, compiles ok, but will not display anything. I'm assuming I've made a mistake with change notification or DataContext or both.
Any insight is appreciated!

WPF binding only operates on properties, not fields.
Therefore, you need change your SoakTimeActual field to a property, like this:
public class Treatment
{
...
public Ticker SoakTimeActual { get; set; }
...
}

Related

Xamarin - How do I inject a property into a ContentView from the ContentPage or ContentPageViewModel

Update: I've updated this a bit to remove the reference to the error. #michal-diviš gave the correction solution to that. However, my larger issue still remains.
I'm new to Xamarin and trying to learn by making a simple email client. I'm trying to set a property on a ContentPage I have created.
The Setup
The MainPage simply has a grid with two columns; the left side features an CollectionView of the inbox, the right side is my custom ContentPage MessageDisplayView. When an email is clicked in the CollectionView, the CurrentMessage property on the MainPageViewModel is updated to the selected item.
The Issue
I'm trying to bind the property MessageDisplayView.Message to the MainPageViewModel.CurrentMessage property, but the contentpage never updates. I've tried with and without BindableProperty, as well as other ideas found while searching Google and Stackoverflow.
The Question
How do I handle setting and updating a property that I would like to live with the ContentPage?
The Code
MainPage.xaml
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:c="Microsoft.Toolkit.Uwp.UI.Controls"
xmlns:vm="clr-namespace:Project.ViewModel"
xmlns:view="clr-namespace:Project.View"
xmlns:fa="clr-namespace:FontAwesome"
x:Class="Project.MainPage">
<ContentPage.BindingContext>
<vm:MainPageViewModel/>
</ContentPage.BindingContext>
<ContentPage.Resources>
<ResourceDictionary>
<ResourceDictionary Source="ResourceDictionaries/EmailResourceDictionary.xaml"/>
</ResourceDictionary>
</ContentPage.Resources>
<Grid x:Name="MainPageGrid">
<!-- other xaml code -->
<view:MessageDisplayView
x:Name="MyDisplayView"
Grid.Column="1"
Message="{Binding CurrentMessage}" <!-- Error -->
/>
</Grid>
</ContentPage>
MainPageViewModel.cs
using MimeKit;
using Project.EmailLogic;
using System.Collections.ObjectModel;
using System.Windows.Input;
using Xamarin.Forms;
using Xamarin.Forms.Xaml;
namespace Project.ViewModel
{
[XamlCompilation(XamlCompilationOptions.Compile)]
public class MainPageViewModel: ObservableObject
{
private MimeMessage currentMessage;
public MimeMessage CurrentMessage
{
get => currentMessage;
set => SetProperty(ref currentMessage, value, nameof(MessageDisplayView.Message));
}
public MainPageViewModel()
{
}
}
}
MessageDisplayView.xaml
<?xml version="1.0" encoding="UTF-8"?>
<ContentView xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:view="clr-namespace:Project.View"
xmlns:vm="clr-namespace:Project.ViewModel"
x:DataType="view:MessageDisplayView"
xmlns:fa="clr-namespace:FontAwesome"
x:Class="Project.View.MessageDisplayView">
<ContentView.Content>
<Grid>
<!-- Various standard xaml things, for example... -->
<!-- Subject Line -->
<Label x:Name="SubjectLine"
Grid.Row="1"
Text="{Binding Message.Subject}"
/>
</Grid>
</ContentView.Content>
</ContentView>
MessageDisplayView.xaml.cs
using MimeKit;
using Xamarin.Forms;
using Xamarin.Forms.Xaml;
namespace Project.View
{
[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class MessageDisplayView : ContentView
{
private MimeMessage message;
public MimeMessage Message
{
get
{
return (MimeMessage)GetValue(MessageProperty);
}
set
{
SetValue(MessageProperty, value);
BodyHtmlViewSource.Html = Message.HtmlBody;
}
}
public BindableProperty MessageProperty =
BindableProperty.Create(nameof(Message), typeof(MimeMessage), typeof(MessageDisplayView));
public HtmlWebViewSource BodyHtmlViewSource { get; set; }
public MessageDisplayView()
{
InitializeComponent();
}
}
}
The problem was the BindableObject was not hearing the notifications of the property changing.
The solution was to add the OnPropertyChanged method to the code behind of the ContentView, not the ContentPageViewModel.
This "solution" correctly updates the property in the code, but it does not update the xaml/UI. I think this might a separate issue.
This confused me at first, when #michal-diviš pointed out the OnPropertyChanged calls, as I thought I was suppose to wire up the event subscription myself in the ContentView code behind. But after stumbling across this article, I realized that the method was required elsewhere.
I feel like a major issue is that there isn't a lot of information about passing data or properties between elements/UserControls/ContentPages, etc. Over the last two days, I've read and watched a fair amount on BindableProperties, but seen very little use of OnPropertyChanged or updating the properties from elsewhere. Perhaps I'm missing the places where it's talked about, or maybe it's more easy or obvious than I realize, but in hindsight, this seems like something that should have been mentioned in every BindableProperty 101.
Beyond the official documentation of course, if anyone knows a good article or video going over sharing/binding/updating properties between classes/views/whatever, I'd love to check that out.
Here's an example of the final, working code:
public partial class MessageDisplayView : ContentView
{
public MimeMessage Message
{
get
{
return (MimeMessage)GetValue(MessageProperty);
}
set
{
SetValue(MessageProperty, value);
}
}
public static BindableProperty MessageProperty =
BindableProperty.Create(nameof(Message), typeof(MimeMessage), typeof(MessageDisplayView), new MimeMessage(),
BindingMode.TwoWay);
protected override void OnPropertyChanged(string propertyName = null)
{
base.OnPropertyChanged(propertyName);
if (propertyName == MessageProperty.PropertyName)
{
if(Message != null)
{
// Update ContentView properties and elements.
}
}
}
Thank you again to #michal-diviš for your help!
Fix
It's the BindableProperty definition!
You have (in the MessageDisplayView.xaml.cs):
public BindableProperty MessageProperty = BindableProperty.Create(nameof(Message), typeof(MimeMessage), typeof(MessageDisplayView));
you need to make it static readonly like this:
public static readonly BindableProperty MessageProperty = BindableProperty.Create(nameof(Message), typeof(MimeMessage), typeof(MessageDisplayView));
Usage of INotifyPropertyChanged
The CurrentMessage property in your MainPageViewModel seems to be the problem. You've created it as a BindableProperty, however, that's meant to be used by user controls, not view models.
What you need in the view model is to implement the INotifyPropertyChanged interface and invoke the PropertyChanged event in the property setter. That is done so the UI will update itseld whenever the CurrentMessage property changes.
Tweak your MainViewModel.cs like this:
using MimeKit;
using Project.EmailLogic;
using Xamarin.Forms;
using System.ComponentModel;
using System.Runtime.CompilerServices;
namespace Project.ViewModel
{
public class MainPageViewModel : INotifyPropertyChanged
{
private MimeMessage currentMessage;
public MimeMessage CurrentMessage
{
get => currentMessage;
set {
currentMessage = value;
OnPropertyChanged(nameof(CurrentMessage))
};
}
public event PropertyChangedEventHandler? PropertyChanged;
protected virtual void OnPropertyChanged([CallerMemberName]string propertyName = "") =>
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
In this example, I've implemented the INotifyPropertyChanged directly in you view model, but a better way to do it is to inherit from a base class that already has that implemented, like this one: ObservableObject from James Montemagno's MVVM Helpers library. The resulting view model would look like this:
using MimeKit;
using Project.EmailLogic;
using MvvmHelpers;
namespace Project.ViewModel
{
public class MainPageViewModel : ObservableObject
{
private MimeMessage currentMessage;
public MimeMessage CurrentMessage
{
get => currentMessage;
set => SetProperty(ref currentMessage, value);
}
}
}
EDIT:
Lately I've been using the CommunityToolkit.Mvvm library instead of Refactored.MvvmHelpers as it's more updated and feature rich.

How to bind two different class properties in DataTemplate

I am trying to bind two properties from different classes in DataTemplate.
<DataTemplate x:Key="DemoItemTemplate" x:DataType="local:DemoInfo">
<NavigationViewItem Visibility="{Binding Visibility, Mode=TwoWay}" Content="{x:Bind Name}"/>
</DataTemplate>
DataType set as DemoInfo for this DataTemplate and Name value updated from DemoInfo.
I have tried view model as source and relative source binding. But Visibility property binding not working from ViewModel class. Any suggest how to achieve this?
Visibility="{Binding Visibility, Source={StaticResource viewModel}}"
AFAIK , you cant use multibinding in UWP , you can try to use Locator What is a ViewModelLocator and what are its pros/cons compared to DataTemplates?
How to bind two different class properties in DataTemplate
If you bind Visibility with StaticResource, please declare ViewModel class in your page Resources like the following.
ViewModel
public class ViewModel
{
public ViewModel()
{
Visibility = false;
}
public bool Visibility { get; set; }
}
Xaml
<Page.Resources>
<local:ViewModel x:Key="ViewModel" />
</Page.Resources>
<DataTemplate x:DataType="local:Item">
<TextBlock
Width="100"
Height="44"
Text="{x:Bind Name}"
Visibility="{Binding Visibility, Source={StaticResource ViewModel}}" />
</StackPanel>
</DataTemplate>
Update
If you want Visibility value changed dynamically at run-time, you need implement INotifyPropertyChanged interface for ViewModel class.
public class ViewModel : INotifyPropertyChanged
{
public ViewModel()
{
Visibility = false;
}
private bool _visibility;
public bool Visibility
{
get
{
return _visibility;
}
set
{
_visibility = value;
OnPropertyChanged();
}
}
public event PropertyChangedEventHandler PropertyChanged;
private void OnPropertyChanged([CallerMemberName] string PropertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(PropertyName));
}
}
For more detail please refer Data binding in depth official document.

Binding two viewModel to one view

i am trying to bind my MasterViewModel where i have initiated two original viewModel to one view. But i am not getting any data so i must be doing the binding wrong. I have found several post
I have tried
in Xaml
<Label
x:Name="SectionRequired"
Grid.Row="2"
HorizontalOptions="End"
IsVisible="{Binding PostViewModel.IsRequired, Source={x:Reference PostViewModel}}"
Text="{x:Static resources:AppResources.AlertRequired}"
TextColor="Red" />
And also followed this solution but i was getting an expcetion that its used lika markup extenstion 'local1:PostViewModel' is used like a markup extension but does not derive from MarkupExtension.
https://stackoverflow.com/questions/50307356/multiple-bindingcontexts-on-same-contentpage-two-different-views
My Master
class MasterPostsViewModel : BaseViewModel
{
public PostViewModel postViewModel { get; set; }
public CategoriesViewModel categoriesViewModel { get; set; }
public MasterPostsViewModel()
{
postViewModel = new PostViewModel();
categoriesViewModel = new CategoriesViewModel();
}
}
}
Conte page
I have set the binding to one field here and that works, buit having to do that for the whole page is not what i want.
MasterPostsViewModel ViewModel;
protected override void OnAppearing()
{
base.OnAppearing();
BindingContext = ViewModel = new MasterPostsViewModel();
NameRequired.IsVisible = ViewModel.postViewModel.IsRequired;
}
Can you help please
instead of
IsVisible="{Binding PostViewModel.IsRequired, Source={x:Reference PostViewModel}}"
just use
IsVisible="{Binding postViewModel.IsRequired}"
your property name is postViewModel is lower case
also, get rid of this line - it will break the binding you have setup in the XAML
NameRequired.IsVisible = ViewModel.postViewModel.IsRequired;

prism null exception on Container.Resolve<IEventAggregator>()

The line Resources.Add("eventAggregator", Container.Resolve()); raises Null exception.
UPDATE
I've added all classes to explain more. As #Axemasta said, there is no need to register IEventAggregator and I removed registration. Now I don't how to connect the Listview EventAggregator behavior to the EventAggregator.
This is whole App.xaml code file.
public partial class App : PrismApplication
{
/*
* The Xamarin Forms XAML Previewer in Visual Studio uses System.Activator.CreateInstance.
* This imposes a limitation in which the App class must have a default constructor.
* App(IPlatformInitializer initializer = null) cannot be handled by the Activator.
*/
public App() : this(null) { }
public App(IPlatformInitializer initializer) : base(initializer) { }
protected override async void OnInitialized()
{
InitializeComponent();
Resources.Add("eventAggregator", Container.Resolve<IEventAggregator>());// Removed on update
FlowListView.Init();
await NavigationService.NavigateAsync("NavigationPage/MainPage");
}
protected override void RegisterTypes(IContainerRegistry containerRegistry)
{
containerRegistry.RegisterForNavigation<NavigationPage>();
containerRegistry.RegisterForNavigation<MainPage>();
}
}
}
The behavior class:
public class ScrollToMyModelBehavior : BehaviorBase<ListView>
{
private IEventAggregator _eventAggregator;
public IEventAggregator EventAggregator
{
get => _eventAggregator;
set
{
if (!EqualityComparer<IEventAggregator>.Default.Equals(_eventAggregator, value))
{
_eventAggregator = value;
_eventAggregator.GetEvent<ScrollToMyModelEvent>().Subscribe(OnScrollToEventPublished);
}
}
}
private void OnScrollToEventPublished(ListItem model)
{
AssociatedObject.ScrollTo(model, ScrollToPosition.Start, true);
}
protected override void OnDetachingFrom(ListView bindable)
{
base.OnDetachingFrom(bindable);
// The Event Aggregator uses weak references so forgetting to do this
// shouldn't create a problem, but it is a better practice.
EventAggregator.GetEvent<ScrollToMyModelEvent>().Unsubscribe(OnScrollToEventPublished);
}
}
The Event class:
public class ScrollToMyModelEvent : PubSubEvent<ListItem>
{
}
The page view model:
public MainPageViewModel(INavigationService navigationService, IEventAggregator eventAggregator)
: base (navigationService)
{
Title = "صفحه اصلی";
ListHeight = 100;
ListWidth = 250;
_eventAggregator = eventAggregator;
Items items = new Items();
ListViewItemSouce = items.GetItems();
MyModels = items.GetItems();
SelectedModel = ListViewItemSouce[3];
_eventAggregator.GetEvent<ScrollToMyModelEvent>().Publish(SelectedModel);
}
The page view:
<StackLayout HorizontalOptions="Center" VerticalOptions="Center" WidthRequest="{Binding ListWidth}" HeightRequest="{Binding ListHeight}"
Grid.Row="1" Grid.Column="1">
<local:NativeListView x:Name="lst3" ItemsSource="{Binding ListViewItemSouce}" Margin="1" BackgroundColor="Transparent" RowHeight="47" HasUnevenRows="false">
<ListView.Behaviors>
<local:ScrollToMyModelBehavior EventAggregator="{StaticResource eventAggregator}" /> // Error raised that there is not such a static property
</ListView.Behaviors>
<ListView.ItemTemplate>
<DataTemplate>
<TextCell Text="{Binding Word}" TextColor="Black"/>
</DataTemplate>
</ListView.ItemTemplate>
</local:NativeListView>
</StackLayout>
You do not need to register IEventAggregator when the app initialises, much like INavigationService or IPageDialog, you can use it straight out of the box!
To use EventAggregator you should do the following things:
Create an Event
You will first need to create an Event (using Prism) that you can pass to the EventAggregator. Your event should inherit from PubSubEvent, you can pass this an object (optional). So your event would look like this:
using System;
using Prism.Events;
namespace Company.App.Namespace.Events
{
public class SampleEvent : PubSubEvent
{
}
}
Looking at a recent app, I most commonly use this when passing data between custom popup views (like a dictionary of params).
Subscribe to the Event
When IEventAggregator fires, anything that has subscribe to the event will execute any code specified. In the class you want to recieved the event you will have to do the following:
Pass the class IEventAggregator through the constructor (prism does the DI afterall)
Initialise a local IEventAggregator for use in this class
Subscribe IEventAggregator to a handler method.
Here is what the code may look like:
public class TheClassListeningForAnEvent
{
private readonly IEventAggregator _eventAggregator;
public TheClassListeningForAnEvent(IEventAggregator eventAggregator)
{
_eventAggregator = eventAggregator;
_eventAggregator.GetEvent<SampleEvent>().Subscribe(OnEventRecieved);
}
void OnEventRecieved()
{
//Do something here
}
}
Fire the Event
Now you have registered for the event, you can fire the event. Pass the IEventAggregator into whatever class you want to fire the event from and use the Publish Method:
public class TheClassPublishingAnEvent
{
private readonly IEventAggregator _eventAggregator;
public TheClassListeningForAnEvent(IEventAggregator eventAggregator)
{
_eventAggregator = eventAggregator;
_eventAggregator.GetEvent<SampleEvent>().Publish();
}
}
Thats the long and the short of it. You could pass anything to the IEventAggregator, you would just need to handle for this in the methods you are subscribing.
Hopefully that is enough to get you going using IEventAggregator!
Just verify if you are adding below code in IOS, Android and UWP projects.
IOS- Appdelegate
public class AppdelegateInitializer : IPlatformInitializer
{
public void RegisterTypes(IUnityContainer container)
{
}
}
Android - MainActivity
public class MainActivityInitializer : IPlatformInitializer
{
public void RegisterTypes(IUnityContainer container)
{
}
}
UWP-- MainPage.cs
public class UwpInitializer : IPlatformInitializer
{
public void RegisterTypes(IUnityContainer container)
{
}
}
My guidance on this has evolved as features have been added to Prism to make this sort of thing even easier.
In the past the reason you would resolve and add the IEventAggregator as a StaticResource is that there was no way to inject this. We now have the ContainerProvider which amazingly allows you to add types in XAML that require Dependency Injection. To start you can refactor your ScrollToBehavior to use a DI Pattern by adding the IEventAggregator as a constructor parameter, removing the Bindable Property (if you choose).
public class ScrollToBehavior : BehaviorBase<ListView>
{
private IEventAggregator _eventAggregator { get; }
public ScrollToBehavior(IEventAggregator eventAggregator)
{
_eventAggregator = eventAggregator;
}
}
As I mentioned you can use the ContainerProvider in XAML to resolve and provide a type that requires DI, as follows:
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:ioc="clr-namespace:Prism.Ioc;assembly=Prism.Forms"
xmlns:behavior="using:AwesomeProject.Behaviors
x:Class="AwesomeProject.Views.ViewA">
<ListView>
<ListView.Behaviors>
<ioc:ContainerProvider x:TypeArguments="behavior:ScrollToBehavior" />
</ListView.Behaviors>
</ListView>
</ContentPage>

Navigating to views inside CarouselView with Prism

I have a MyPage with a CarouselView and two buttons below it. The buttons are for navigating between ContentView views inside the CarouselView:
[CarouselView]
[Prev] [Next]
ContentViewA and ContentViewB are inside of CarouselView
The MyPageViewModel has commands for the previous and next buttons:
class MyPageViewModel : BindableBase
{
public ICommand ShowPrevCommand { get; private set;}
public ICommand ShowNextCommand { get; private set;}
}
How do I implement the commands to make the CarouselView show the views?
According to documentation here
In Prism, the concept of navigating to a View or navigating to a
ViewModel does not exist. Instead, you simply navigate to an
experience, or a unique identifier, which represents the target view
you wish to navigate to in your application
so I was thinking I could use INavigationService.
I was thinking I could implement my own NavigationService and on NavigateAsync I could check if current page is MyPage. If it is, I could set the view inside of CarouselView to the view based on the navigation name parameter.
I am however not sure how to implement and override Prism's navigation service.
Can Prism for Xamarin Forms do something like this?
It does not have to be that complicated. CarouselView has the bindable property Position, which you can bind to a property of your viewmodel
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:forms="clr-namespace:Xamarin.Forms;assembly=Xamarin.Forms.CarouselView">
<ContentPage.Content>
<forms:CarouselView Position="{Binding CarouselPosition}">
<!-- whatever to display in the CarouselView -->
</form:CarouselView>
</ContentPage.Content>
</ContentPage>
In your viewmodel you can implement th navigation the following way:
class MyPageViewModel : BindableBase
{
public MyPageViewModel()
{
ShowPrevCommand = new Command(ShowPrev);
ShowNextCommand = new Command(ShowNext);
}
public ICommand ShowPrevCommand { get; private set;}
public ICommand ShowNextCommand { get; private set;}
void OnShowPrev()
{
CarouselPosition--;
}
void OnShowNext()
{
CarouselPosition++;
}
public int CarouselPosition
{
get => _carouselPosition;
set
{
if(value == _carouselPosition)
{
return;
}
this._carouselPosition = value;
PropertyChanges?.Invoke(this, new PropertyChangedEventArgs(CarouselPosition));
}
}
}
Just to get the gist. Of course you'll have to handle cases like overflows (i.e. CarouselPosition exceeds the number of views in the carousel), etc.

Resources