mvvmcross navigate to viewmodel from tabbed - c#

I have a Xamarin Forms application using mvvmcross. There I have navigation via TabbedPages. Each page has a xaml + code behind and viewmodel.
Relevant code for first page:
<?xml version="1.0" encoding="utf-8" ?>
<pages:BaseTabbedPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:pages="clr-namespace:ABBI_XPlat_3.Pages;assembly=ABBI_XPlat_3"
x:Class="ABBI_XPlat_3.Pages.DeviceListPage"
Title="Discover devices"
x:Name="DevicePage">
<pages:BaseTabbedPage.Resources>
<ResourceDictionary>
<DataTemplate x:Key="DeviceItemTemplate"> ... </DataTemplate>
</ResourceDictionary>
</pages:BaseTabbedPage.Resources>
<pages:BaseTabbedPage.Children>
<pages:BasePage Title="Scan for devices">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto"></RowDefinition>
<RowDefinition Height="*"></RowDefinition>
<RowDefinition Height="Auto"></RowDefinition>
</Grid.RowDefinitions>
<StackLayout BackgroundColor="#FF6969" Padding="10" IsVisible="{Binding IsStateOn, Converter={StaticResource InverseBoolean}}">
<Label Text="{Binding StateText}" FontSize="18" HorizontalTextAlignment="Center"></Label>
</StackLayout>
<ListView Grid.Row="1" ItemsSource="{Binding Devices}" SelectedItem="{Binding SelectedDevice, Mode=TwoWay}"
IsPullToRefreshEnabled="True"
RefreshCommand="{Binding RefreshCommand}"
IsRefreshing="{Binding IsRefreshing, Mode=OneWay}"
RowHeight="80"
ItemTemplate="{StaticResource DeviceItemTemplate}">
</ListView>
<StackLayout Grid.Row="2" Orientation="Horizontal">
<Button Text="Connect" Command="{Binding ConnectToSelectedCommand}" HorizontalOptions="FillAndExpand"/>
<Button Text="Stop Scan" Command="{Binding StopScanCommand}" HorizontalOptions="End"/>
<ActivityIndicator IsRunning="{Binding IsRefreshing}"
HeightRequest="24"
WidthRequest="24"
VerticalOptions="Center"
HorizontalOptions="End"/>
</StackLayout>
</Grid>
</pages:BasePage>
<pages:ServiceListPage Title="Services"/>
<pages:OtherTabbedPage Title="Services"/>
</pages:BaseTabbedPage.Children>
</pages:BaseTabbedPage>
I am able to call different viewmodels from buttons in my main view model using:
public MvxCommand ConnectToSelectedCommand => new MvxCommand(ConnectToSelectedDeviceAsync, CanDisplayServices);
private async void ConnectToSelectedDeviceAsync()
{
ShowViewModel<ServiceListViewModel>(new MvxBundle(new Dictionary<string, string> { { DeviceIdKey, SystemDevices.FirstOrDefault().Id.ToString() } }));
}
within my main ViewModel. But I want to be able to use the tabs to navigate between ViewModels. At the moment if I click on a tab, then it brings up the page, but without the associated ViewModel.
Help please!

So what you have to do to get MvvmCross to bind the Pages to the VMs is have a MvxTabbedPage as the Root TabbedPosition & have your pages that go in the tabs as the Detail TabbedPosition. Then in the MvxTabbedPage's ViewModel, you have to Navigate to all the Detail Tab's ViewModels. Here is an example.
namespace NameSpace
{
// Tabbed Detail Page
[MvxTabbedPagePresentation(Title = "Home", Icon = "ic_home_black.png")]
[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class HomePage : MvxContentPage<HomeViewModel>
{
public HomePage()
{
InitializeComponent();
}
}
// Tabbed Root Page
[MvxTabbedPagePresentation(TabbedPosition.Root, WrapInNavigationPage = true)]
[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class TabbedPage : MvxTabbedPage<TabbedViewModel>
{
public TabbedProjectDetailsPage()
{
InitializeComponent();
}
}
// Tabbed Detail ViewModel
public class HomeViewModel : MvxViewModel
{
IMvxNavigationService _navigation;
public HomeViewModel(IMvxNavigationService navigation)
{
_navigation = navigation;
}
}
// Tabbed Root ViewModel
public class TabbedViewModel : MvxNavigationViewModel
{
public TabbedProjectDetailsViewModel(IMvxLogProvider log, IMvxNavigationService navigation) : base(log, navigation)
{
}
MvxCommand _navHome;
public ICommand NavigateHome
{
get
{
_navHome = _navHome ?? new MvxCommand(async () =>
{
await NavigationService.Navigate<HomeViewModel>();
});
return _navHome;
}
}
public void ShowViewModels()
{
this.NavigateHome.Execute(null);
}
bool appeared = false;
public override void ViewAppearing()
{
base.ViewAppearing();
if (!appeared)
{
ShowViewModels();
}
appeared = true;
}
}
}

Finally managed to solve the problem. It was so simple that I could not find an answer anywhere. I just had to add a bindingcontext to the codebehind of the page.
public ServiceListPage()
{
InitializeComponent();
this.BindingContext = new ViewModels.ServiceListViewModel(Plugin.BLE.CrossBluetoothLE.Current.Adapter, UserDialogs.Instance);
}

Related

Xaml button Command does not fire

I'm using the CameraView from the XamarinCommunityToolKit. Why button command "Capture" does not fire when I click it? Is it because code is running in emulator and not in actual physical phone with a real camera?
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:xct="http://xamarin.com/schemas/2020/toolkit"
x:Class="App2.Views.CapturePage">
<StackLayout>
<xct:CameraView
x:Name="cameraView"
CaptureMode="Photo"
FlashMode="Off"
HorizontalOptions="FillAndExpand"
MediaCaptured="CameraView_MediaCaptured"
OnAvailable="CameraView_OnAvailable"
VerticalOptions="FillAndExpand" />
<Button
x:Name="doCameraThings"
Command="{Binding CaptureCommand, Source={x:Reference cameraView}}"
IsEnabled="True"
Text="Capture" />
<Image
x:Name="previewPicture"
Aspect="AspectFit"
BackgroundColor="LightGray"
HeightRequest="250"
IsVisible="False" />
</StackLayout>
</ContentPage>
ViewModel looks like this:
public class CaptureViewModel : BaseViewModel
{
public Command CaptureCommand { get; }
public CaptureViewModel()
{
CaptureCommand = new Command(CapturePageClicked);
}
private async void CapturePageClicked()
{
//Some code here
}
}
From Xamarin Community Toolkit CameraView, there is one Icommand ShutterCommand for CameraView, so you can binding ShutterCommand to Button.Command.
<StackLayout>
<xct:CameraView
x:Name="cameraview"
CaptureMode="Photo"
FlashMode="On"
HorizontalOptions="FillAndExpand"
MediaCaptured="cameraView_MediaCaptured"
VerticalOptions="FillAndExpand"
/>
<Button
x:Name="doCameraThings"
Command="{Binding ShutterCommand, Source={x:Reference cameraview}}"
IsEnabled="True"
Text="Capture" />
<Image
x:Name="previewPicture"
Aspect="AspectFit"
BackgroundColor="LightGray"
HeightRequest="250"
IsVisible="False" />
</StackLayout>
public partial class Page6 : ContentPage
{
public Page6()
{
InitializeComponent();
}
private void cameraView_MediaCaptured(object sender, Xamarin.CommunityToolkit.UI.Views.MediaCapturedEventArgs e)
{
switch (cameraview.CaptureMode)
{
default:
case CameraCaptureMode.Default:
case CameraCaptureMode.Photo:
previewPicture.IsVisible = true;
previewPicture.Rotation = e.Rotation;
previewPicture.Source = e.Image;
break;
case CameraCaptureMode.Video:
previewPicture.IsVisible = false;
break;
}
}
}
But you can also binding another command to Button.click in Viewmodel.
<xct:CameraView
x:Name="cameraview"
CaptureMode="Photo"
FlashMode="On"
HorizontalOptions="FillAndExpand"
MediaCaptured="cameraView_MediaCaptured"
VerticalOptions="FillAndExpand"
/>
<Button
x:Name="doCameraThings"
Command="{Binding CaptureCommand}"
IsEnabled="True"
Text="Capture" />
<Image
x:Name="previewPicture"
Aspect="AspectFit"
BackgroundColor="LightGray"
HeightRequest="250"
IsVisible="False" />
public class CaptureViewModel
{
public Command CaptureCommand { get; }
public CaptureViewModel()
{
CaptureCommand = new Command(CapturePageClicked);
}
private async void CapturePageClicked()
{
//Some code here
}
}
Binding ViewModel to current page BindingContext
public Page6()
{
InitializeComponent();
this.BindingContext = new CaptureViewModel();
}
simple sample about CameraView, you can take a look:
https://github.com/xamarin/XamarinCommunityToolkit/blob/main/samples/XCT.Sample/Pages/Views/CameraViewPage.xaml

Xamarin.Forms dynamically change Master page content

I have a simple app with Master-Detail page.
It looks similar:
And I want to dynamically change Master page content.
E.g. on Detail page there are some Button and then you click on it - some items from Master page dissapear.
I've tried to find some item properties like item1.isVisible=False but found nothing.
Is there any way I can do it?
MainPage code:
public partial class MainPage : MasterDetailPage
{
public MainPage()
{
InitializeComponent();
masterPage.listView.ItemSelected += OnItemSelected;
}
void OnItemSelected(object sender, SelectedItemChangedEventArgs e)
{
var item = e.SelectedItem as MasterPageItem;
if (item != null)
{
Detail = new NavigationPage((Page)Activator.CreateInstance(item.TargetType));
masterPage.listView.SelectedItem = null;
IsPresented = false;
}
}
}
MainPage XAML:
<MasterDetailPage xmlns=....>
<MasterDetailPage.Master>
<views:MasterPage x:Name="masterPage" />
</MasterDetailPage.Master>
<MasterDetailPage.Detail>
<NavigationPage>
<x:Arguments>
<views:SomePage/>
</x:Arguments>
</NavigationPage>
</MasterDetailPage.Detail>
MasterPage XAML:
<StackLayout>
<ListView x:Name="listView" x:FieldModifier="public" Margin="10,50,0,0">
<ListView.ItemsSource>
<x:Array Type="{x:Type local:MasterPageItem}">
<local:MasterPageItem Title="Home" TargetType="{x:Type views:HomePage}" IconSource="nav_icon_home"/>
<local:MasterPageItem Title="Settings" TargetType="{x:Type views:HomePage}" IconSource="nav_icon_settings" />
<local:MasterPageItem Title="My Profile" TargetType="{x:Type views:HomePage}" IconSource="nav_icon_profile" />
<local:MasterPageItem Title="Help" TargetType="{x:Type views:HomePage}" IconSource="nav_icon_help" />
<local:MasterPageItem Title="About" TargetType="{x:Type views:AboutPage}" IconSource="nav_icon_about"/>
</x:Array>
</ListView.ItemsSource>
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<Grid Padding="10,10,10,10" ColumnSpacing="10">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="30"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<Image Source="{Binding IconSource}"/>
<Label Grid.Column="1" Text="{Binding Title}" TextColor="White" VerticalOptions="Center"/>
</Grid>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</StackLayout>
MasterPage items:
public class MasterPageItem
{
public string Title { get; set; }
public string IconSource { get; set; }
public Type TargetType { get; set; }
}
So I've implemented INotifyPropertyChanged inside MasterPageItem:
public class MasterPageItem : INotifyPropertyChanged
{
public string Title { get; set; }
public string IconSource { get; set; }
public Type TargetType { get; set; }
public event PropertyChangedEventHandler PropertyChanged = delegate { };
private bool isVisible;
public bool IsVisible
{
get { return isVisible; }
set
{
isVisible = value;
PropertyChanged(this, new PropertyChangedEventArgs("IsVisible"));
}
}
}
But how can I bind this to my MasterPage?
In the end I've implemented 2 different MasterPages, so I can switch between them when needed.
So I have 2 MainPages the 1st one refers to MasterPage1:
<MasterDetailPage.Master>
<views:MasterPage1 x:Name="masterPage1" />
</MasterDetailPage.Master>
<MasterDetailPage.Detail>
<NavigationPage>
<x:Arguments>
<views:SomePage1/>
</x:Arguments>
</NavigationPage>
</MasterDetailPage.Detail>
The 2nd MainPage2 - to MasterPage2:
<MasterDetailPage.Master>
<views:MasterPage2 x:Name="masterPage2" />
</MasterDetailPage.Master>
<MasterDetailPage.Detail>
<NavigationPage>
<x:Arguments>
<views:SomePage2/>
</x:Arguments>
</NavigationPage>
</MasterDetailPage.Detail>
I know it's not the best solution, but for my case it's enough.
First of all, learn how to ask; https://stackoverflow.com/help/how-to-ask
You expect us to understand how you build up your views and modify them, without even showing a single line of code.
Generally speaking, you can change the View of the Master Page by changing the Master-Property of a Xamarin.Forms.MasterDetailPage. If you assigned a Xamarin.Forms.ContentPage to the Master-Property, you can acces it by ((ContentPage)YourMasterDetailPage.Master).Content.
Im sure this question has been answered already 100 times and follows the basic structure of xamarin forms.
Learn MasterDetailPage from scratch here:
https://learn.microsoft.com/en-US/xamarin/xamarin-forms/app-fundamentals/navigation/master-detail-page
Since you provided some code now, here's a little example:
void OnItemSelected(object sender, SelectedItemChangedEventArgs e)
{
var item = e.SelectedItem as MasterPageItem;
if (item != null)
{
Detail = new NavigationPage((Page)Activator.CreateInstance(item.TargetType));
item.IsVisible = false; //this would make the clicked item invisible
masterPage.listView.SelectedItem = null;
IsPresented = false;
}
}

Navigate between views in Xamarin (visual studio) PCL project

I cant find a way to implement an onClick event on a button that will allow the application to navigate between the login and the second view.
How can I do that ?
Here is what i did
I created a method in my LoginViewModel.cs file that should redirect me to the second view.
class LoginViewModel
{
private async Task SecondView_Click()
{
App.Current.MainPage = new NavigationPage(new SecondView());
}
}
Then I've defined a BindingContext in my Login.cs
public partial class Login : ContentPage
{
public Login()
{
InitializeComponent();
BindingContext = new LoginViewModel();
}
}
Then I define a button in my Login.xaml that has a binded command property
<StackLayout
VerticalOptions="CenterAndExpand">
<Entry StyleId="UsernameEntry"
Placeholder="Username"
Text="{Binding Username}" />
<Entry StyleId="PasswordEntry"
Placeholder="password"
Text="{Binding Password}" />
<Button
StyleId="btn_connexion"
Text="Connexion"
Command="{Binding connexion}" />
<Button
StyleId="btn_testSecondView"
Text="Test 2nd View"
Command="{Binding SecondView_Click}"></Button>
</StackLayout>
This works for me
PAGE 1 XAML
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="TestRelativeLayout.MyPage1"
Title="TabbedPage">
<StackLayout>
<Button Clicked="Handle_Clicked" Text = "Press">
</Button>
</StackLayout>
</ContentPage>
PAGE 1 XAML.CS
using Xamarin.Forms;
namespace TestRelativeLayout
{
public partial class MyPage1 : ContentPage
{
public MyPage1()
{
InitializeComponent();
}
public void Handle_Clicked(object sender, System.EventArgs e)
{
Application.Current.MainPage = new NavigationPage(new MyPage2());
}
}
}
Try to remove
private async Task
and use
void
private async Task SecondView_Click()
{
App.Current.MainPage = new NavigationPage(new SecondView());
}
Here is what I did.
I found that there is a "clicked" property on that prompt an intellisense dropdown with a "new event handler".
<StackLayout
VerticalOptions="CenterAndExpand">
<Entry StyleId="UsernameEntry"
Placeholder="Username"
Text="{Binding Username}" />
<Entry StyleId="PasswordEntry"
Placeholder="password"
Text="{Binding Password}" />
<Button
StyleId="btn_connexion"
Text="Connexion"
Clicked="connexion" />
<Button
StyleId="btn_testSecondView"
Text="Test 2nd View"
Clicked="SecondView_Click"></Button>
</StackLayout>
Once i did that it created a method in the code behind "Login.xaml.cs".
From there I just paste the navigation method and it worked
private async Task SecondView_Click()
{
App.Current.MainPage = new NavigationPage(new SecondView());
}
The fact that it is a PCL project makes it difficult to find the right information because everything you find on the internet concerns the ios/android solution and not the portable solution.

Why are my User Settings saved only the first time this method is called?

I have a WPF MVVM app, which gets its data from a user setting which is an ObservableCollection of type Copyable (a custom class) called Copyables. Within the main view model (ClipboardAssistantViewModel), I set the source of a CollectionViewSource to Copyables. This is then bound to an ItemsControl in the main view (MainWindow). The DataTemplate for this ItemsControl is a user control, 'CopyableControl', which is essentially a button, but with attached properties that allow me to bind data and commands to it.
When a user clicks on a CopyableControl, a view model (DefineCopyableViewModel) is added to an ObservableCollection of those in ClipboardAssistantViewModel, and that collection is bound to an ItemsControl in MainWindow. The DataTemplate of this is a UserControl called DefineCopyableControl, which is set up in such a way that the current values associated with the clicked Copyable are bound to textboxes in the DefineCopyableControl for editing.
My problem: There is a method in DefineCopyableViewModel, EditCopyable(), which only works on the first run (its job is to save the user settings once any edits have taken place and the user clicks "OK"). If I click the CopyableControl and make an edit, then click "OK", then click it again, make another edit, then click "OK", then close the application and open it again, only the first edit has been saved (even though the UI was updated with the edited value both times). It seems to have something to do with the data-binding need to be "refreshed"; please see the comments in this method in the code for my findings around this.
My code is as follows:
Model:
namespace ClipboardAssistant.Models
{
public class Copyable : INotifyPropertyChanged
{
// INotifyPropertyChanged implementation
private string name;
public string Name
{
get { return name; }
set
{
if (value != name)
{
name = value;
NotifyPropertyChanged("Name");
}
}
}
private string textToCopy;
public string TextToCopy
{
get { return textToCopy; }
set
{
if (value != textToCopy)
{
textToCopy = value;
NotifyPropertyChanged("TextToCopy");
}
}
}
public Copyable() { }
public Copyable(string Name, string TextToCopy)
{
this.Name = Name;
this.TextToCopy = TextToCopy;
}
}
}
ViewModels:
namespace ClipboardAssistant.ViewModels
{
public class ClipboardAssistantViewModel : INotifyPropertyChanged
{
// INotifyPropertyChanged Implementation
public CollectionViewSource CopyablesView { get; set; }
public ObservableCollection<DefineCopyableViewModel> Definers { get; set; }
public CopyableClickCommand CopyableClickCommand { get; set; }
public ClipboardAssistantViewModel()
{
Definers = new ObservableCollection<DefineCopyableViewModel>();
CopyablesView = new CollectionViewSource();
CopyablesView.Source = Properties.Settings.Default.Copyables;
CopyableClickCommand = new CopyableClickCommand(this);
EditModeClickCommand = new EditModeClickCommand(this);
}
public void RefreshCopyables()
{
// Both these methods of refreshing appear to have the same effect.
Properties.Settings.Default.Copyables = (ObservableCollection<Copyable>)CopyablesView.Source;
CopyablesView.Source = Properties.Settings.Default.Copyables;
}
public void EditCopyable(Copyable Copyable)
{
Definers.Add(new DefineCopyableViewModel(Copyable, this));
}
}
}
namespace ClipboardAssistant.ViewModels
{
public class DefineCopyableViewModel : INotifyPropertyChanged
{
// INotifyPropertyChanged Implementation
public ClipboardAssistantViewModel MyParent { get; set; }
public Copyable Copyable { get; set; }
public DefinerOKClickCommand DefinerOKClickCommand { get; set; }
public DefineCopyableViewModel(Copyable Copyable, ClipboardAssistantViewModel MyParent)
{
this.Copyable = Copyable;
this.MyParent = MyParent;
DefinerOKClickCommand = new DefinerOKClickCommand(this);
}
public void EditCopyable()
{
// Refresh, save, no refresh, save -> doesn't save second edit.
// Save, refresh, save, no refresh -> does save second edit.
MessageBoxResult r = MessageBox.Show("Refresh?", "Refresh", MessageBoxButton.YesNo);
if (r == MessageBoxResult.Yes)
{
MyParent.RefreshCopyables();
}
// These two MessageBox methods (save and refresh) can be swapped around (see above comments).
MessageBoxResult s = MessageBox.Show("Save?", "Save", MessageBoxButton.YesNo);
if (s == MessageBoxResult.Yes)
{
Properties.Settings.Default.Save();
}
MyParent.Definers.Remove(this);
}
}
}
MainWindow:
<Window x:Class="ClipboardAssistant.Views.MainWindow" x:Name="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:vm="clr-namespace:ClipboardAssistant.ViewModels"
xmlns:ctrls="clr-namespace:ClipboardAssistant.Controls"
mc:Ignorable="d"
Title="Clipboard Assistant" Height="400" Width="700">
<Window.DataContext>
<vm:ClipboardAssistantViewModel />
</Window.DataContext>
<Grid>
<Grid Margin="15">
<Grid.RowDefinitions>
<RowDefinition Height="*" />
<RowDefinition Height="20" />
<RowDefinition Height="30" />
</Grid.RowDefinitions>
<ItemsControl ItemsSource="{Binding CopyablesView.View}">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<WrapPanel Orientation="Vertical" />
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<ItemsControl.ItemTemplate>
<DataTemplate>
<ctrls:CopyableControl Copyable="{Binding}"
ClickCopyable="{Binding DataContext.CopyableClickCommand, ElementName=mainWindow}" />
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
<DockPanel Grid.Row="2">
<Button x:Name="btnEditCopyableMode" HorizontalAlignment="Left" DockPanel.Dock="Left"
Content="Edit" Margin="0,0,10,0" Command="{Binding EditModeClickCommand}" />
</DockPanel>
</Grid>
<ItemsControl ItemsSource="{Binding Definers}">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<Grid />
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<ItemsControl.ItemTemplate>
<DataTemplate>
<ctrls:DefineCopyableControl Copyable="{Binding DataContext.Copyable}"
ClickCancel="{Binding DataContext.DefinerCancelClickCommand, ElementName=mainWindow}" />
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</Grid>
</Window>
CopyableControl:
<UserControl x:Class="ClipboardAssistant.Controls.CopyableControl" x:Name="copyableControl"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:local="clr-namespace:ClipboardAssistant.Controls"
mc:Ignorable="d" d:DesignHeight="75" d:DesignWidth="200">
<Grid Width="200" Height="75">
<Button Command="{Binding ClickCopyable, ElementName=copyableControl}"
CommandParameter="{Binding Copyable, ElementName=copyableControl}"
Content="{Binding Copyable.Name, ElementName=copyableControl}"
Style="{StaticResource CopyableMainButtonStyle}" />
</Grid>
</UserControl>
namespace ClipboardAssistant.Controls
{
public partial class CopyableControl : UserControl
{
public static readonly DependencyProperty ClickCopyableProperty =
DependencyProperty.Register("ClickCopyable", typeof(ICommand), typeof(CopyableControl));
public ICommand ClickCopyable
{
get { return (ICommand)GetValue(ClickCopyableProperty); }
set { SetValue(ClickCopyableProperty, value); }
}
public static readonly DependencyProperty CopyableProperty =
DependencyProperty.Register("Copyable", typeof(Copyable), typeof(CopyableControl));
public Copyable Copyable
{
get { return (Copyable)GetValue(CopyableProperty); }
set { SetValue(CopyableProperty, value); }
}
public CopyableControl()
{
InitializeComponent();
}
}
}
DefineCopyableControl:
<UserControl x:Class="ClipboardAssistant.Controls.DefineCopyableControl" x:Name="defineCopyableControl"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
mc:Ignorable="d"
d:DesignHeight="300" d:DesignWidth="500">
<Grid x:Name="MainGrid" Background="Blue">
<Grid Width="200" Height="180">
<Grid.RowDefinitions>
<RowDefinition Height="30" />
<RowDefinition Height="30" />
<RowDefinition Height="10" />
<RowDefinition Height="30" />
<RowDefinition Height="30" />
<RowDefinition Height="20" />
<RowDefinition Height="30" />
</Grid.RowDefinitions>
<Label Grid.Row="0" Content="Name" Foreground="White" />
<TextBox Grid.Row="1" Text="{Binding Copyable.Name}" x:Name="tbN" />
<Label Grid.Row="3" Content="Copyable Text" Foreground="White" />
<TextBox Grid.Row="4" Text="{Binding Copyable.TextToCopy}" x:Name="tbTTC" />
<DockPanel Grid.Row="6">
<Button Width="70" Content="OK" DockPanel.Dock="Right" HorizontalAlignment="Right"
Command="{Binding DefinerOKClickCommand}"
CommandParameter="{Binding ElementName=defineCopyableControl}" />
</DockPanel>
</Grid>
</Grid>
</UserControl>
public partial class DefineCopyableControl : UserControl
{
public static readonly DependencyProperty CopyableProperty =
DependencyProperty.Register("Copyable", typeof(Copyable), typeof(DefineCopyableControl));
public Copyable Copyable
{
get { return (Copyable)GetValue(CopyableProperty); }
set { SetValue(CopyableProperty, value); }
}
public DefineCopyableControl()
{
InitializeComponent();
}
}
Commands:
namespace ClipboardAssistant.ViewModels.Commands
{
public class CopyableClickCommand : ICommand
{
public ClipboardAssistantViewModel ViewModel { get; set; }
public CopyableClickCommand(ClipboardAssistantViewModel viewModel)
{
ViewModel = viewModel;
}
public event EventHandler CanExecuteChanged;
public bool CanExecute(object parameter)
{
return true;
}
public void Execute(object parameter)
{
Copyable cp = (Copyable)parameter;
ViewModel.EditCopyable(cp);
}
}
}
namespace ClipboardAssistant.ViewModels.Commands
{
public class DefinerOKClickCommand : ICommand
{
public DefineCopyableViewModel ViewModel { get; set; }
public DefinerOKClickCommand(DefineCopyableViewModel viewModel)
{
ViewModel = viewModel;
}
public event EventHandler CanExecuteChanged;
public bool CanExecute(object parameter)
{
return true;
}
public void Execute(object parameter)
{
ViewModel.EditCopyable();
}
}
}
Settings:
namespace ClipboardAssistant.Properties {
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "14.0.0.0")]
internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase {
private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings())));
public static Settings Default {
get {
return defaultInstance;
}
}
[global::System.Configuration.UserScopedSettingAttribute()]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
public global::System.Collections.ObjectModel.ObservableCollection<ClipboardAssistant.Models.Copyable> Copyables {
get {
return ((global::System.Collections.ObjectModel.ObservableCollection<ClipboardAssistant.Models.Copyable>)(this["Copyables"]));
}
set {
this["Copyables"] = value;
}
}
}
}
I'm assuming you are using Visual Studio. In that case, in the My Project do you have the settings listed in the settings tab?
I ran into the same issue a while back where I tried to programatically create/save/update settings and was unsucessful until I created the setting in the Settings tab. Once that was complete I was able to make my saves as necessary.
The you just use
MySettings.Default.SettingName = value
MySettings.Default.Save()
Hope this helps!

How to show a view using Catel

I am developing a simple app with Catel. I have previously used ReactiveUI and am having a little trouble getting started with Catel. I have a basic MainWindow. In there I have a toolbar with some buttons. When a button is selected I would like to show in the bottom pane of the application a user control (based on what they selected). So far I have one basic view that has a listview in it and then a view model behind it. I need help in figuring out how to show that view when the button is selected. Thank you for your help. Here is what I have so far. As you can see, when the 'ExecutePlayersButtonCommand' in the mainviewmodel is run, i want it to show the players view. I am not sure how to get this. I can get it to come up in a popup but that is not what i want. In reactiveui I can do it with the Router.Navigate function. Not sure how to do it here.
<catel:DataWindow xmlns:Controls="clr-namespace:FootballSim.Controls;assembly=FootballSim.Controls"
xmlns:RedfoxSoftwareCustomControls="clr-namespace:RedfoxSoftwareCustomControls;assembly=RedfoxSoftwareCustomControls"
x:Class="FootballSim.Views.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:catel="http://catel.codeplex.com"
xmlns:views="clr-namespace:FootballSim.Views"
Style="{StaticResource {x:Type Window}}"
ShowInTaskbar="True" ResizeMode="CanResize" SizeToContent="Manual"
WindowStartupLocation="Manual" WindowState="Maximized" Icon="/FootballSim;component/redfox_software_48x48.ico">
<!-- Resources -->
<catel:DataWindow.Resources>
</catel:DataWindow.Resources>
<!-- Content -->
<catel:StackGrid x:Name="LayoutRoot">
<catel:StackGrid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
</catel:StackGrid.RowDefinitions>
<DockPanel>
<StackPanel DockPanel.Dock="Top">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="*" />
<RowDefinition Height="50" />
<RowDefinition Height="100*" />
</Grid.RowDefinitions>
<RedfoxSoftwareCustomControls:WpfCustomApplicationMenuBar x:Name="CustomMenuBar" Grid.Row="0" />
<StackPanel Grid.Row="1">
<Button HorizontalAlignment="Left" Command="{Binding PlayersButtonCommand}" Background="Transparent">
<StackPanel>
<Image Source="/FootballSim;component/Resources/People_white_48.png" Width="30"></Image>
<TextBlock Text="Players" Foreground="White" HorizontalAlignment="Center"/>
</StackPanel>
</Button>
</StackPanel>
<DockPanel LastChildFill="True" Grid.Row="2">
<ContentControl Content="{Binding contentObject}" />
<!--<views:PlayersView DataContext="{Binding PlayerProviders}" />-->
</DockPanel>
</Grid>
</StackPanel>
</DockPanel>
</catel:StackGrid>
</catel:DataWindow>
using Catel.Windows;
using FootballSim.Scripts;
using FootballSim.Services;
using FootballSim.ViewModels;
using System;
using System.ComponentModel;
using Catel.MVVM.Views;
using Catel.Windows.Data;
using Catel.MVVM;
namespace FootballSim.Views
{
public partial class MainWindow : DataWindow
{
private RedfoxMessage logger = new RedfoxMessage();
private PopulateDatabase database = new PopulateDatabase();
public MainWindow() : base(DataWindowMode.Custom)
{
try
{
InitializeComponent();
logger.LogMessage("Starting application.");
CustomMenuBar.AboutButtonClickEvent += CustomMenuBar_AboutButtonClickEvent;
}
catch (Exception e)
{
RedfoxMessage.LogMessage(e, NLog.LogLevel.Error);
}
}
private void CustomMenuBar_AboutButtonClickEvent(object sender, System.EventArgs args)
{
(DataContext as IMainWindowViewModel).AboutButtonCommand.Execute(null);
}
}
}
using Catel.Data;
using Catel.IoC;
using Catel.MVVM;
using Catel.MVVM.Services;
using FootballSim.Models;
using FootballSim.Scripts;
using FootballSim.Views;
using System.Collections.Generic;
using System.Windows;
namespace FootballSim.ViewModels
{
public interface IMainWindowViewModel
{
Command PlayersButtonCommand { get; }
Command AboutButtonCommand { get; }
List<Player> PlayerProviders { get; }
Player SelectedPlayerProvider { get; }
object ContentObject { get; }
}
/// <summary>
/// MainWindow view model.
/// </summary>
public class MainWindowViewModel : ViewModelBase, IMainWindowViewModel
{
//private readonly IUIVisualizerService _uiVisualizerService;
private PopulateDatabase _populateDatabase;
public static readonly PropertyData PlayerProvidersProperty = RegisterProperty("PlayerProviders", typeof(List<Player>));
public static readonly PropertyData SelectedPlayerProviderProperty = RegisterProperty("SelectedPlayerProvider", typeof(Player));
public Command PlayersButtonCommand { get; private set; }
public Command AboutButtonCommand { get; private set; }
public object ContentObject { get; set; }
public MainWindowViewModel() : base()
{
//var dependencyResolver = this.GetDependencyResolver();
//_uiVisualizerService = dependencyResolver.Resolve<IUIVisualizerService>();
_populateDatabase = new PopulateDatabase();
PlayerProviders = _populateDatabase.Players;
var pv = new PlayersView();
pv.DataContext = PlayerProviders;
ContentObject = pv;
PlayersButtonCommand = new Command(ExecutePlayersButtonCommand);
AboutButtonCommand = new Command(ExecuteAboutButtonCommand);
}
private void ExecutePlayersButtonCommand()
{
PlayerProviders = _populateDatabase.Players;
MessageBox.Show("Players");
}
private void ExecuteAboutButtonCommand()
{
var aboutView = new AboutView();
aboutView.ShowDialog();
}
public List<Player> PlayerProviders
{
get
{
return GetValue<List<Player>>(PlayerProvidersProperty);
}
set
{
SetValue(PlayerProvidersProperty, value);
}
}
public Player SelectedPlayerProvider
{
get
{
return GetValue<Player>(SelectedPlayerProviderProperty);
}
set
{
SetValue(SelectedPlayerProviderProperty, value);
}
}
//protected override void Initialize()
//{
// SelectedPlayerProvider = PlayerProviders[0];
//}
public override string Title { get { return "FootballSim"; } }
}
}
<catel:UserControl x:Class="FootballSim.Views.PlayersView"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:catel="http://catel.codeplex.com"
xmlns:views="clr-namespace:FootballSim.Views"
xmlns:viewmodels="clr-namespace:FootballSim.ViewModels"
xmlns:models="clr-namespace:FootballSim.Models;assembly=FootballSim.Core">
<!-- Resources -->
<UserControl.Resources>
</UserControl.Resources>
<!-- Content -->
<catel:StackGrid>
<catel:StackGrid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
</catel:StackGrid.RowDefinitions>
<Label Content="{Binding Title}" Foreground="White" Grid.Row="0" />
<Label Content="Here goes your real content" Foreground="White" Grid.Row="1"/>
<ListBox Grid.Row="2" ItemsSource="{Binding PlayersCollection}" SelectedItem="{Binding SelectedPlayer}">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel>
<Label Content="{Binding ColumnValue}" />
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
<!--<views:PlayersView Grid.Column="1" DataContext="{Binding SelectedPlayer}" />-->
</catel:StackGrid>
</catel:UserControl>
namespace FootballSim.Views
{
using Catel.Windows.Controls;
using FootballSim.ViewModels;
public partial class PlayersView : UserControl
{
public PlayersView()
{
InitializeComponent();
}
}
}
namespace FootballSim.ViewModels
{
using Catel.MVVM;
using FootballSim.Models;
using System.Collections.Generic;
/// <summary>
/// UserControl view model.
/// </summary>
public class PlayersViewModel : ViewModelBase, IPlayersViewModel
{
public List<Player> Players { get; protected set; }
public PlayersViewModel(List<Player> players) : base()
{
Players = players;
}
public override string Title { get { return "View model title"; } }
// TODO: Register models with the vmpropmodel codesnippet
// TODO: Register view model properties with the vmprop or vmpropviewmodeltomodel codesnippets
// TODO: Register commands with the vmcommand or vmcommandwithcanexecute codesnippets
}
}
There are several ways of navigating in Catel:
IUIVisualizerService => show other dialogs
INavigationService => navigate to pages / close application / etc
Maybe it's a good idea for you to read the getting started guide of Catel.

Categories