Mahapps, themes not applying to user controls - c#

I have a single MetroWindow which loads with default Color. I have an option for user to change the style. In the window I use a Content control to set the user control dynamically from code behind when initializing this window (This window is initialized from another application so there is no app.xaml and I use the resources in the window itself). The code of the main windows is below. In the User Control I am using some labels and a tab control. On the window I have an option for user to be able to change the theme choosing from available themes (as in your demo project). In all labels I use dynamics resources.
When the window loads for first time the default color is applied and all inner controls have the same theme as well. When I change the theme from window top, the window border, title, glow changes but the inner control stays the old theme (like the tab control headers etc.) I have tried everything but that does not seem to change.
Below is my code:
<Controls:MetroWindow x:Class="Test.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:Controls="clr-namespace:MahApps.Metro.Controls;assembly=MahApps.Metro"
Title="MainWindow" Height="300" Width="300" ShowMaxRestoreButton="False" ShowMinButton="False"
BorderBrush="{DynamicResource HighlightBrush}"
GlowBrush="{DynamicResource HighlightBrush}" WindowStartupLocation="CenterScreen"
ResizeMode="NoResize" WindowTransitionsEnabled="False" TitleCaps="True"
BorderThickness="1">
<Window.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="pack://application:,,,/MahApps.Metro;component/Styles/Controls.xaml" />
<ResourceDictionary Source="pack://application:,,,/MahApps.Metro;component/Styles/Fonts.xaml" />
<ResourceDictionary Source="pack://application:,,,/MahApps.Metro;component/Styles/Colors.xaml" />
<ResourceDictionary Source="pack://application:,,,/MahApps.Metro;component/Styles/Accents/Blue.xaml" />
<ResourceDictionary Source="pack://application:,,,/MahApps.Metro;component/Styles/Accents/BaseLight.xaml" />
<ResourceDictionary Source="/Test;component/Resources/Icons.xaml" />
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
</Window.Resources>
<Border Margin="5" BorderBrush="Transparent" BorderThickness="0">
<ContentControl x:Name="ChildContentControl"
HorizontalAlignment="Stretch"
VerticalAlignment="Stretch">
</ContentControl>
</Border>
</Controls:MetroWindow>
My code behind for the window:
public partial class MainWindow : MetroWindow
{
public MainWindow()
{
InitializeComponent();
this.Initialize();
}
public MainWindow(string title, UserControl childControl)
{
try
{
InitializeComponent();
this.Title = title;
this.ChildContentControl.Content = childControl;
}
catch (Exception de)
{
throw de;
}
}
}
My User control XAML
<UserControl x:Class="Test.UCDemo"
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:sys="clr-namespace:System;assembly=mscorlib"
xmlns:local="clr-namespace:Test"
xmlns:Controls="clr-namespace:MahApps.Metro.Controls;assembly=MahApps.Metro"
mc:Ignorable="d"
d:DesignHeight="300" d:DesignWidth="300">
<UserControl.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="/Test;component/Resources/Icons.xaml" />
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
</UserControl.Resources>
<Border>
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<DockPanel Grid.Row="0" LastChildFill="True">
<Grid Height="60" DockPanel.Dock="Bottom">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="auto"/>
<ColumnDefinition Width="5"/>
</Grid.ColumnDefinitions>
<Button Grid.Column="1" Margin="5,0,5,0" Width="50" Height="50"
Style="{DynamicResource MetroCircleButtonStyle}" Command="{Binding OKCommand}">
<Rectangle Width="20"
Height="20"
Fill="{Binding Path=Foreground, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Button}}}">
<Rectangle.OpacityMask>
<VisualBrush Stretch="Fill"
Visual="{StaticResource appbar_check}" />
</Rectangle.OpacityMask>
</Rectangle>
</Button>
</Grid>
<Grid DockPanel.Dock="Top" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" Background="Transparent"
SnapsToDevicePixels="True"
ScrollViewer.HorizontalScrollBarVisibility="Hidden" ScrollViewer.VerticalScrollBarVisibility="Hidden">
<Grid.RowDefinitions>
<RowDefinition Height="*"></RowDefinition>
<RowDefinition Height="auto"></RowDefinition>
</Grid.RowDefinitions>
<Grid Grid.Row="0">
<Grid.Resources>
<ResourceDictionary Source="pack://application:,,,/MahApps.Metro;component/Styles/Controls.AnimatedSingleRowTabControl.xaml" />
</Grid.Resources>
<TabControl Margin="0,10,0,0" TabStripPlacement="Left" ItemsSource="{Binding Catalogs}" SelectedItem="{Binding SelectedCatalog}">
<TabControl.ItemTemplate>
<!-- this is the header template-->
<DataTemplate>
<TextBlock Text="{Binding Path=CaptionCat}" Foreground="{DynamicResource HighlightBrush}" FontSize="14" Margin="0,0,0,10" />
</DataTemplate>
</TabControl.ItemTemplate>
<TabControl.ContentTemplate>
<DataTemplate>
<ItemsControl ItemsSource="{Binding DataContext.SelectedCatalog.Books,RelativeSource={RelativeSource AncestorType={x:Type TabControl}}}">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<WrapPanel ScrollViewer.VerticalScrollBarVisibility="Disabled"/>
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<ItemsControl.ItemTemplate>
<DataTemplate>
<Controls:Tile Height="125" Width="300" IsEnabled="{Binding IsEnabled}" Title="{Binding CaptionBook}"/>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</DataTemplate>
</TabControl.ContentTemplate>
</TabControl>
</Grid>
</Grid>
</DockPanel>
</Grid>
</Border>
</UserControl>
My User control Code behind:
public partial class UCDemo : UserControl
{
private VMDemo CatalogVM { set; get; }
public UCDemo()
{
try
{
InitializeComponent();
this.DataContext = new VMDemo();
}
catch (Exception de)
{
throw de;
}
}
}
And Finally here is how I call the window and embedded user control from hosted application code:
private void ShowDemoUI()
{
try
{
var child = new UILibrary.UCDemo();
UILibrary.MainWindow window = new UILibrary.MainWindow("Book catalog", child);
window.Height = 450;
window.Width = 700;
window.ShowDialog();
}
catch (Exception de)
{
throw de;
}
}

I think you have 2 options to solve this.
Create your Test.UCDemo as DataTemplate for the VMDemo type and pass the VMDemo for this template to the Content, so your ContentControl will automatically do the magic for you (it's just only a suggestion, i don't tested it)
Put the resources in your Test.UCDemo too.

You need to move all your ResourceDictionaries in the App.xaml
After that I think you need to look at the Theme Manager.
Here is what I've done. In this example all my Content Control have the save Theme even if I change the Theme with a button click:
public ShellView()
{
this.InitializeComponent();
var theme = ThemeManager.DetectAppStyle(Application.Current);
ThemeManager.ChangeAppStyle(Application.Current, ThemeManager.GetAccent("Blue"), theme.Item1);
}
private void Button_Click(object sender, RoutedEventArgs e)
{
var theme = ThemeManager.DetectAppStyle(Application.Current);
ThemeManager.ChangeAppStyle(Application.Current, ThemeManager.GetAccent("Cyan"), theme.Item1);
}
The code need to be in the code behing of your Window (In my case it's ShellView.cs) for you I will assume that it's MainWindow.cs
Here is an other example with a Custom Theme.
public ShellView()
{
this.InitializeComponent();
ThemeManager.AddAccent("YourAccent", new Uri("pack://application:,,,/YourAccent.xaml"));
// Set your Custom Theme when the Window start
var theme = ThemeManager.DetectAppStyle(Application.Current);
ThemeManager.ChangeAppStyle(Application.Current, ThemeManager.GetAccent("YourAccent"), theme.Item1);
}
private void Button_Click(object sender, RoutedEventArgs e)
{
// Change the Theme to Cyan on a simple button click
var theme = ThemeManager.DetectAppStyle(Application.Current);
ThemeManager.ChangeAppStyle(Application.Current, ThemeManager.GetAccent("Cyan"), theme.Item1);
}

Related

Window startup location at mouse cursor

I am working on a WPF Project with Caliburn Micro. Please consider the following code snippets:
PopupWindowView.xaml
<Window x:Class="PTSRDesktopUI.Views.PopupWindowView"
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:PTSRDesktopUI.Views"
mc:Ignorable="d" ShowInTaskbar="True"
ResizeMode="NoResize" SizeToContent="Height" FontSize="24"
MouseDown="Window_MouseDown" Background="#FFF7F7F7" Icon="/Images/infoicon_8Ve_icon.ico"
Title="Pfad Info" Height="300" Width="500">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<TextBlock FontSize="20" Grid.Column="1" Text="{Binding Path=Path}" Margin="10 10 10 10"
HorizontalAlignment="Center" VerticalAlignment="Center" IsEnabled="False"
FontFamily="Segoe UI Light"/>
</Grid>
</Window>
PopupWindowViewModel.cs
using Caliburn.Micro;
using PTSRDesktopUI.Models;
namespace PTSRDesktopUI.ViewModels
{
public class PopupWindowViewModel : Screen
{
private string _path;
public PopupWindowViewModel(ChangesModel model)
{
_path = model.ParameterPfad;
}
public string Path
{
get { return _path; }
set
{
_path = value;
NotifyOfPropertyChange(() => Path);
}
}
}
}
OverviewView.xaml
<DataGridTemplateColumn CellStyle="{StaticResource DataGridCellCentered}" Header="Info">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<Button BorderThickness="0" Height="30" Width="30"
Style="{StaticResource {x:Static ToolBar.ButtonStyleKey}}"
cal:Message.Attach="ShowPath($this)">
<Image Source="/Images/infoicon.png"/>
</Button>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
OverviewViewModel.cs
private readonly IWindowManager manager = new WindowManager();
public void ShowPath(ChangesModel model)
{
manager.ShowWindow(new PopupWindowViewModel(model), null, null);
}
All this does is, when the Button in the DataGrid is pressed, the PopupWindow pops up and displays some data. It all works fine. The only thing I cannot seem to figure out is how to display the new PopupWindow at the same location where the clicked Button is, or rather where my mouse pointer is. I have read all the other StackOverflow questions regarding this problem but none of them does the trick for me. I either get an error or it just does not work. Anyone has any ideas how to solve this?

UWPToolkit - What is a ItemTemplate and how do I make one for my AdaptiveGrid?

Im currently trying to use the AdaptiveGrid in the toolkit to display Some images that then can be clicked on to lead to pages, I think this ItemTemplate is what provides the images in the example. Is this the same as any DataTemplate? I cant find any information online about these or docs.
<Controls:AdaptiveGridView Name="AdaptiveGridViewControl"
OneRowModeEnabled="False"
ItemHeight="200"
DesiredWidth="300"
SelectionMode="Single"
IsItemClickEnabled="True"
ItemTemplate="{StaticResource PhotosTemplate}"/>
I've tried the following, I get no errors but nothing shows up when I run it locally except the command bar:
Mainpage.xaml:
<Page
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:MobileAppProject"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:viewModels="using:ViewModels"
xmlns:Controls="using:Microsoft.Toolkit.Uwp.UI.Controls"
x:Class="MobileAppProject.MainPage"
mc:Ignorable="d">
<Page.Resources>
<DataTemplate x:Key="AdaptTemplate">
<Grid
Background="White"
BorderBrush="Black"
BorderThickness="1">
<Image
Source="{Binding Image}"
Stretch="UniformToFill"
HorizontalAlignment="Center"
VerticalAlignment="Center"/>
</Grid>
</DataTemplate>
</Page.Resources>
<Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
<ScrollViewer VerticalScrollMode="Auto" VerticalScrollBarVisibility="Auto">
<Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}" Margin="12,10,12,12">
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="*"/>
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
<StackPanel Margin="0,0,0,10"/>
<Grid Grid.Row="1">
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition/>
</Grid.RowDefinitions>
<Controls:AdaptiveGridView Name="AdaptiveGridViewControl"
OneRowModeEnabled="False"
ItemHeight="200"
DesiredWidth="300"
SelectionMode="Single"
IsItemClickEnabled="True"
ItemTemplate="{StaticResource AdaptTemplate}"/>
<StackPanel VerticalAlignment="Bottom" Margin="0,24,0,0" Grid.Row="1" Background="{ThemeResource SystemControlBackgroundAccentBrush}">
<CommandBar x:Name="cmdbar"
IsOpen="{Binding IsChecked, ElementName=isopentoggle, Mode=TwoWay}"
IsSticky="{Binding IsChecked, ElementName=isstickytoggle, Mode=TwoWay}"
ClosedDisplayMode="{Binding SelectedItem.Content, ElementName=combobox}">
<CommandBar.SecondaryCommands>
<AppBarButton Label="Menu Item 1"/>
<AppBarButton Label="Menu Item 2"/>
<AppBarButton Label="Menu Item 3"/>
<AppBarButton Label="Menu Item 4"/>
</CommandBar.SecondaryCommands>
<AppBarButton Icon="Accept" Label="Accept"/>
<AppBarToggleButton Icon="Contact" Label="Contact"/>
</CommandBar>
<Image HorizontalAlignment="Left" Source="Assets/storeLogo-sdk.png" Stretch="None"/>
</StackPanel>
</Grid>
<!-- Status Block for providing messages to the user. Use the
NotifyUser() method to populate the message -->
<TextBlock x:Name="StatusBlock" Grid.Row="2" Margin="12, 10, 12, 10" Visibility="Collapsed"/>
</Grid>
</ScrollViewer>
</Grid>
</Page>
Mainpage.xaml.cs:
private ObservableCollection<AdaptItem> picItems_;
private ObservableCollection<AdaptItem> PicItems
{
get
{
return picItems_;
}
set
{
picItems_ = value;
}
}
public MainPage()
{
this.InitializeComponent();
picItems_ = AdaptItem.AdaptList();
this.DataContext = PicItems;
}
AdaptTemplate.cs for filling the AdaptGrid:
public class AdaptItem
{
public String Image
{
get;
set;
}
}
public static ObservableCollection<AdaptItem> AdaptList()
{
ObservableCollection<AdaptItem> pics = new ObservableCollection<AdaptItem>()
{
new AdaptItem
{
Image = "Assets/01.jpg"
},
new AdaptItem
{
Image = "Assets/02.jpg"
},
new AdaptItem
{
Image = "Assets/03.jpg"
},
new AdaptItem
{
Image = "Assets/04.jpg"
},
new AdaptItem
{
Image = "Assets/05.jpg"
}
};
return pics;
}
You can check how the template is used in the UWP Toolkit sample app or in the sample code on GitHub:
<Controls:AdaptiveGridView Name="AdaptiveGridViewControl"
OneRowModeEnabled="False"
ItemHeight="200"
DesiredWidth="300"
SelectionMode="Single"
IsItemClickEnabled="True"
ItemTemplate="{StaticResource PhotosTemplate}">
<Controls:AdaptiveGridView.Resources>
<DataTemplate x:Key="PhotosTemplate">
<Grid
Background="White"
BorderBrush="Black"
BorderThickness="1">
<Image
Source="{Binding Thumbnail}"
Stretch="UniformToFill"
HorizontalAlignment="Center"
VerticalAlignment="Center"/>
</Grid>
</DataTemplate>
</Controls:AdaptiveGridView.Resources>
</Controls:AdaptiveGridView>
In short - yes, the ItemTemplate works the same way as any other DataTemplate.

How to remove the Close Tabs in Caliburn Micro MVVM application?

I have built an application in MVVM using Caliburn Micro. I currently have the closetab working on all my tabs, and it closes all tabs apart from the first three, which are Home, Payment, Notes however, I would like it to NOT show the close tab icon on the first three tabs as shown in my AppViewModel code:
<TabControl x:Name="Items" Grid.Row="1" Visibility="{Binding Visibility, Converter={StaticResource boolToVis}}">
<TabControl.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<!-- The Tab Names Binding with DisplayName-->
<TextBlock Text="{Binding DisplayName}" />
<!-- The Tab Close Icon-->
<Button Content="x" x:Name="CloseTab" cal:Message.Attach="CloseTab" Style="{DynamicResource appTabCloseButton}" Visibility="{Binding Visibility, Converter={StaticResource boolToVis}}"/>
</StackPanel>
</DataTemplate>
</TabControl.ItemTemplate>
</TabControl>
My AppViewModel code behind for the close tab:
public void CloseTab()
{
if(ActiveItem.DisplayName == "Home" || ActiveItem.DisplayName == "Payment" || ActiveItem.DisplayName == "Notes")
{
MessageBox.Show("This Tab Cannot Be closed.","Permanent Tab");
} else {
DeactivateItem(ActiveItem, close: true);
}
}
My App.xaml code for the boolToVis:
<Application x:Class="WPF.Test.App"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:WPF.Test.App">
<Application.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary>
<local:Bootstrapper x:Key="bootstrapper" />
<BooleanToVisibilityConverter x:Key="boolToVis" />
</ResourceDictionary>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="/Global.WPF.UserControls;component/Resources/brushes.xaml" />
<ResourceDictionary Source="/Global.WPF.UserControls;component/Resources/CommonControls.xaml" />
<ResourceDictionary Source="/Global.WPF.UserControls;component/Resources/menuItems.xaml" />
<ResourceDictionary Source="pack://application:,,,/Fluent;Component/Themes/Generic.xaml" />
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
</Application.Resources>
</Application>
and finally the visibility for the binding:
bool _visibility;
public bool Visibility
{
get { return _visibility; }
set
{
_visibility = value;
NotifyOfPropertyChange("Visibility");
}
}
I would be happy for any suggestions as I'm totally lost!!
Create a Guard Panel that can be used to show/hide the button.
<TabControl x:Name="Items" Grid.Row="1" Visibility="{Binding Visibility, Converter={StaticResource boolToVis}}">
<TabControl.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<!-- The Tab Names Binding with DisplayName-->
<TextBlock Text="{Binding DisplayName}" />
<Border x:Name="CanCloseTab">
<!-- The Tab Close Icon-->
<Button Content="x" x:Name="CloseTab" cal:Message.Attach="CloseTab" Style="{DynamicResource appTabCloseButton}" />
</Border>
</StackPanel>
</DataTemplate>
</TabControl.ItemTemplate>
</TabControl>
Then create a guard property
public bool CanCloseTab {
get {
return !(ActiveItem.DisplayName == "Home"
|| ActiveItem.DisplayName == "Payment"
|| ActiveItem.DisplayName == "Notes");
}
}
By convention the view should automatically bind the CanCloseTab property to the visibility of the panel (Border) so that when false it will not display. If the panel was not there the guard property would have also automatically disabled the button.
This should now allow the CloseTab method to be refactored for simplicity.
public void CloseTab() {
if(CanCloseTab) {
DeactivateItem(ActiveItem, close: true);
}
}

How to set the source of a CollectionViewSource

I'm trying to create a little tool for Microsofts Team Founation Server (which is not that important for the question). However i'm not that familiar with C# and WPF and even after reading through some tutorials about bindings and resources, i can't figure out, how to get the code working.
With the Visual Studio Designer i created a little form, that just has some buttons and a textbox that should display the name of the authorized user.
Unfortunately, after logging in, an ArgumentException is thrown. So the question is : How can i bind my local TfsTeamProjectCollection to tfsTeamProjectCollectionViewSource?
Thanks for your help!
<Window
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:TFSBranchingTool"
xmlns:sys="clr-namespace:System;assembly=mscorlib"
xmlns:diag="clr-namespace:System.Diagnostics;assembly=WindowsBase"
xmlns:Client="clr-namespace:Microsoft.TeamFoundation.Client;assembly=Microsoft.TeamFoundation.Client" x:Class="TFSBranchingTool.MainWindow"
mc:Ignorable="d"
Title="TFSBranchingTool" Height="360" Width="560"
x:Name="wnd" Loaded="wnd_Loaded">
<Window.Resources>
<CollectionViewSource x:Key="tfsTeamProjectCollectionViewSource" d:DesignSource="{d:DesignInstance {x:Type Client:TfsTeamProjectCollection}, CreateList=True}" Source="{Binding}"/>
</Window.Resources>
<Grid Margin="0,0,0,-1">
<Menu x:Name="menu" VerticalAlignment="Top" Background="{DynamicResource {x:Static SystemColors.MenuBrushKey}}" d:IsLocked="True">
<MenuItem Header="File">
<MenuItem Header="Exit" HorizontalAlignment="Left" Click="exit_application_click"/>
</MenuItem>
<MenuItem Header="Team">
<MenuItem Header="Connect to server" HorizontalAlignment="Left" Margin="0" Width="201" Click="connect_to_server_click"/>
</MenuItem>
</Menu>
<StatusBar x:Name="statusbar" VerticalAlignment="Bottom" Margin="0,0,0,-2" MinHeight="16">
<StatusBarItem x:Name="connection_status" Content="{Binding TeamProjectCollection.AuthorizedIdentity.DisplayName}" HorizontalAlignment="Left"/>
</StatusBar>
<Grid x:Name="grid1" DataContext="{StaticResource tfsTeamProjectCollectionViewSource}" HorizontalAlignment="Left" Margin="138,122,0,0" VerticalAlignment="Top">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition Width="Auto"/>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
<Label Content="Display Name:" Grid.Column="0" HorizontalAlignment="Left" Margin="3" Grid.Row="0" VerticalAlignment="Center"/>
<TextBox x:Name="displayNameTextBox" Grid.Column="1" HorizontalAlignment="Left" Height="23" Margin="3" Grid.Row="0" Text="{Binding AuthorizedIdentity.DisplayName, Mode=TwoWay, NotifyOnValidationError=true, ValidatesOnExceptions=true}" VerticalAlignment="Center" Width="120"/>
</Grid>
</Grid>
And here is the logic:
using Microsoft.TeamFoundation.Client;
using System.Windows;
namespace TFSBranchingTool
{
/// <summary>
/// Interaktionslogik für MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
private TfsTeamProjectCollection m_tfs_team_project_collection;
public MainWindow()
{
InitializeComponent();
}
private void exit_application_click(object sender, RoutedEventArgs e)
{
Close();
}
private void connect_to_server_click(object sender, RoutedEventArgs e)
{
TeamProjectPicker team_project_picker = new TeamProjectPicker(TeamProjectPickerMode.NoProject, false);
if (team_project_picker.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
m_tfs_team_project_collection = team_project_picker.SelectedTeamProjectCollection;
System.Windows.Data.CollectionViewSource tfsTeamProjectCollectionViewSource = ((System.Windows.Data.CollectionViewSource)(this.FindResource("tfsTeamProjectCollectionViewSource")));
//ArgumentException :
//Additional Information: "<TFS-URI>" is an invalid value for the property "Source".
tfsTeamProjectCollectionViewSource.Source = m_tfs_team_project_collection;
}
}
}
}
You have to use GetDefaultView static Method of CollectionViewSource class to give the view your collection.
Here is what you have to do.
tfsTeamProjectCollectionViewSource.Source = CollectionViewSource.GetDefaultView(m_tfs_team_project_collection);
Also you haven't set the data context of the window as Window itself.
Try doing this.
public MainWindow()
{
InitializeComponent();
DataContext = this;
}
By doing the above, any binding in the xaml code will look for its source in the window.
Another thing I have found wrong in your code is that you have defined
tfsTeamProjectCollectionViewSource as a local variable rather than a data member of the Window.
Try making it a data member like m_tfs_team_project_collection and then see what happens.

WPF page navigation in c#

I am trying to learn c# and WPF application. Here I am trying to redirect from one WPF page(MainWindow.xaml) to another(HandWash.xaml) on a button click event. But the following code is throwing NULLReferenceException.
This is the MainWindow.xaml file.
<Window x:Class="MyApplication.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
d:DesignHeight="720" d:DesignWidth="1284"
Title="StartPage" WindowStartupLocation="CenterScreen" WindowStyle="None" WindowState="Maximized" Closed="Window_Closed">
<Window.Background>
<ImageBrush ImageSource="/Images/StartPage.png"></ImageBrush>
</Window.Background>
<Grid>
<Button Content="Hand Wash" Height="794" HorizontalAlignment="Left" Name="HandWash" VerticalAlignment="Top" Width="353" FontSize="50" Background="Transparent" BorderThickness="0" Style="{StaticResource {x:Static ToolBar.ButtonStyleKey}}" Click="HandWash_Click"/>
<Button Content="Bathing" Height="794" HorizontalAlignment="Left" Margin="390,0,0,0" Name="Bathing" VerticalAlignment="Top" Width="301" FontSize="50" Background="Transparent" BorderThickness="0" Style="{StaticResource {x:Static ToolBar.ButtonStyleKey}}" Click="Bathing_Click"/>
<Button Content="Nail-Clip" Height="794" HorizontalAlignment="Left" Margin="730,0,0,0" Name="NailClip" VerticalAlignment="Top" Width="295" FontSize="50" Background="Transparent" BorderThickness="0" Style="{StaticResource {x:Static ToolBar.ButtonStyleKey}}" Click="NailClip_Click"/>
<Button Content="Teeth Brush" Height="794" HorizontalAlignment="Left" Margin="1067,0,0,0" Name="TeethBrush" VerticalAlignment="Top" Width="310" FontSize="50" Background="Transparent" BorderThickness="0" Style="{StaticResource {x:Static ToolBar.ButtonStyleKey}}" Click="TeethBrush_Click"/>
</Grid>
</Window>
Background code for this:
private void TeethBrush_Click(object sender, RoutedEventArgs e)
{
try
{
TeethBrush teeth = new TeethBrush(myarg);
NavigationService navService = NavigationService.GetNavigationService(this);
navService.Navigate(teeth); // NULL REFERENCE EXCEPTION at this line
}
catch (NullReferenceException ex)
{
System.Windows.MessageBox.Show(ex.Message);
}
}
This is the code for TeethBrush.xaml :
<Page x:Class="MyApplication.TeethBrush"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
d:DesignHeight="720" d:DesignWidth="1284"
Title="TeethBrush">
<Grid>
</Grid>
<Page.Background>
<ImageBrush ImageSource="C:\Users\Tonmoy\Documents\Visual Studio 2010\Projects\MyKinectApp\MyKinectApp\Images\StartPage.png"></ImageBrush>
</Page.Background>
</Page>
and the background code is:
public TeethBrush(Myargs arg)
{
InitializeComponent();
//Rest of the code
}
Please help....
You need to have a frame in main window where contents of Pages will be hosted.
If you add the following namespace to MainWindow:
xmlns:local="clr-namespace:System.Windows.Controls;assembly=PresentationFramework"
you can define a frame somewhere, e.g. in your grid:
<Grid>
<local:Frame x:Name="mainFrame">
</local:Frame>
....
Then you can navigate from your event handler like so:
TeethBrush teeth = new TeethBrush(myarg);
this.mainFrame.Navigate(teeth);

Categories