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.
Related
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?
I'm making an application using Caliburn.Micro(for easy data binding and stuff) and MahApps.Metro(for designing).
I've created a View name 'MainView' which has HamburgerMenu of MahApps.
My issue is data binding is working fine under HamburgerMenu.ContentTemplate tag
Here is my HamburgerMenu.ContentTemplate xaml.
<Page x:Class="Sample.Views.MainView"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:cal="http://www.caliburnproject.org"
xmlns:mah="clr-namespace:MahApps.Metro.Controls;assembly=MahApps.Metro"
xmlns:iconPacks="http://metro.mahapps.com/winfx/xaml/iconpacks"
xmlns:utils="clr-namespace:Omni.WindowsClient.Utils"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:local="clr-namespace:Omni.WindowsClient.Views"
mc:Ignorable="d"
d:DesignHeight="300"
d:DesignWidth="600">
<Page.Resources>
<DataTemplate x:Key="HamburgerMenuItem"
DataType="{x:Type mah:HamburgerMenuItem}">
<Grid Height="48">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="48" />
<ColumnDefinition />
</Grid.ColumnDefinitions>
<Image Margin="12"
HorizontalAlignment="Center"
VerticalAlignment="Center"
Source="{Binding Glyph}"
Stretch="UniformToFill" />
<TextBlock Grid.Column="1"
VerticalAlignment="Center"
FontSize="16"
Foreground="White"
Text="{Binding Label}" />
</Grid>
</DataTemplate>
</Page.Resources>
<Grid>
<mah:HamburgerMenu x:Name="HamburgerMenuControl"
SelectedIndex="0"
ItemTemplate="{StaticResource HamburgerMenuItem}"
OptionsItemTemplate="{StaticResource HamburgerMenuItem}"
IsPaneOpen="True"
DisplayMode="CompactInline"
cal:Message.Attach="[Event ItemClick] = [Action ShowDetails(HamburgerMenuControl.SelectedItem)]"
DataContext="{Binding RelativeSource={RelativeSource self}}">
<mah:HamburgerMenu.ItemsSource>
<mah:HamburgerMenuItemCollection>
<mah:HamburgerMenuItem Label="System Status">
<mah:HamburgerMenuItem.Tag>
<iconPacks:PackIconFontAwesome Width="22"
Height="22"
HorizontalAlignment="Center"
VerticalAlignment="Center"
Kind="Tasks" />
</mah:HamburgerMenuItem.Tag>
</mah:HamburgerMenuItem>
<mah:HamburgerMenuItem Label="Inbox">
<mah:HamburgerMenuItem.Tag>
<iconPacks:PackIconFontAwesome Width="22"
Height="22"
HorizontalAlignment="Center"
VerticalAlignment="Center"
Kind="Inbox" />
</mah:HamburgerMenuItem.Tag>
</mah:HamburgerMenuItem>
<mah:HamburgerMenuItem.Tag>
<iconPacks:PackIconFontAwesome Width="22"
Height="22"
HorizontalAlignment="Center"
VerticalAlignment="Center"
Kind="Certificate" />
</mah:HamburgerMenuItem.Tag>
</mah:HamburgerMenuItem>
</mah:HamburgerMenuItemCollection>
</mah:HamburgerMenu.ItemsSource>
<mah:HamburgerMenu.ContentTemplate>
<DataTemplate DataType="{x:Type mah:HamburgerMenuItem}">
<Grid utils:GridUtils.RowDefinitions="48,*">
<!--cal:Action.TargetWithoutContext="{Binding ElementName=HamburgerMenuControl, Path=DataContext}"-->
<Border Grid.Row="0"
Background="{DynamicResource MahApps.Metro.HamburgerMenu.PaneBackgroundBrush}">
<TextBlock x:Name="Header"
HorizontalAlignment="Center"
VerticalAlignment="Center"
FontSize="24"
Foreground="White" />
<!--Text="{Binding Path=Header, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"-->
</Border>
<Frame Grid.Row="1"
cal:Message.Attach="RegisterFrame($source)"
DataContext="{x:Null}"
NavigationUIVisibility="Hidden" />
</Grid>
</DataTemplate>
</mah:HamburgerMenu.ContentTemplate>
</mah:HamburgerMenu>
</Grid>
</Page>
and respective view model code is:
using Caliburn.Micro;
using MahApps.Metro.Controls;
using System.Windows.Controls;
namespace Sample.ViewModels
{
public class MainViewModel : Screen
{
private readonly SimpleContainer _container;
private INavigationService _navigationService;
private string _header;
public string HeaderTitle
{
get { return _header; }
set
{
_header = value;
NotifyOfPropertyChange();
}
}
public MainViewModel(SimpleContainer container)
{
this._container = container;
DisplayName = "Main";
}
public void RegisterFrame(Frame frame)
{
_navigationService = new FrameAdapter(frame);
_container.Instance(_navigationService);
_navigationService.NavigateToViewModel(typeof(SystemStatusViewModel));
HeaderTitle = "System Status";
}
public void ShowDetails(HamburgerMenuItem menuItem)
{
switch (menuItem.Label)
{
case "System Status":
_navigationService.NavigateToViewModel(typeof(SystemStatusViewModel));
HeaderTitle = "System Status";
break;
case "Inbox":
_navigationService.NavigateToViewModel(typeof(InboxViewModel));
HeaderTitle = "Inbox";
break;
default:
break;
}
}
}
}
I want to change View in frame under HamburgerMenu.ContentTemplate when I click on menu item.
Like System Status view is SystemStatusView
and Inbox view is InboxView.
My code is working fine (it changes the view in frame and change the Header label too) if I don't use HamburgerMenu.ContentTemplate. But I want to use HamburgerMenu.ContentTemplate to work with HamburgerMenu.
Thanks!
If it's working fine if you don't use HamburgerMenu.ContentTemplate, but stops working when you do, the problem is probably with you overwriting the default template in a way that doesn't support all functionalities of a control.
I'd suggest you to use Blend to get the default HamburgerMenu.ContentTemplate, then just edit it to your needs, without changing too much (keep in mind that names of controls used as a template may have a crucial meaning, so be careful what you are editing).
If you don't know how to use Blend to get your control's template, here is a simple tutorial described in a documentation of Telerik controls (don't worry, it works the same for all controls). You just need to create copy of a HamburgerMenu.ContentTemplate, paste it to your application and you are good to go (editing).
I try to make a "email messenger". I have two windows. Main window, there is ribbon with bookmarks and one button (New message). This button invoke second window NewMessage. The Mainwindow is owner of the NewMessage window.
MainWindow:
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void Button_Click(object sender, RoutedEventArgs e)
{
NewMessage newmessage = new NewMessage();
newmessage.Show();
}
}
}
MainWindow XAML:
<Window x:Class="Messenger.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:Messenger"
mc:Ignorable="d"
Title="MainWindow" Height="350" Width="525">
<Grid>
<Button Content="New Message" Height="20" Width="80
" HorizontalAlignment="Left" Margin="35,46,0,0" VerticalAlignment="Top" Click="Button_Click" />
<TabControl HorizontalAlignment="Left" Height="254" Margin="34,44,0,0" VerticalAlignment="Top" Width="461" Background="{x:Null}" SelectedIndex="1">
<TabItem Header="Delivered" Visibility="Hidden" Width="80">
<Grid Background="#FFE5E5E5"/>
</TabItem>
<TabItem Header="Delivered" Visibility="Visible" Width="80">
<Grid Background="#FFE5E5E5"/>
</TabItem>
<TabItem Header="Sent" Width="80">
<Grid Background="#FFE5E5E5"/>
</TabItem>
<TabItem Header="Trash" Width="80">
<Grid Background="#FFE5E5E5"/>
</TabItem>
</TabControl>
</Grid>
NewMessage:
public partial class NewMessage : Window
{
public NewMessage()
{
InitializeComponent();
}
private void Button_Click(object sender, RoutedEventArgs e)
{
this.Close();
}
}
}
NewMessage XAML:
<Window x:Class="Messenger.NewMessage"
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:Messenger"
mc:Ignorable="d"
Title="NewMessage" Height="351.047" Width="814.398">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="4*"/>
<ColumnDefinition Width="27*"/>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="23*"/>
<RowDefinition Height="24*"/>
<RowDefinition Height="243*"/>
<RowDefinition Height="31*"/>
</Grid.RowDefinitions>
<Label Grid.Row="0" Content="Komu" HorizontalAlignment="Left" VerticalAlignment="Top"/>
<TextBox Grid.Row="0" Grid.Column="1" HorizontalAlignment="Stretch" VerticalAlignment="Top" />
<Label Grid.Row="1" Content="Předmět" HorizontalAlignment="Left" VerticalAlignment="Top"/>
<TextBox Grid.Row="1" Grid.Column="1" HorizontalAlignment="Stretch" VerticalAlignment="Top" />
<RichTextBox HorizontalAlignment="Left" Height="243" Grid.Row="2" VerticalAlignment="Top" Width="806" Grid.ColumnSpan="2">
<FlowDocument>
<Paragraph>
<Run Text="Sem zadejte text zprávy"/>
</Paragraph>
</FlowDocument>
</RichTextBox>
<Button Grid.Row="3" Content="Odeslat" Grid.Column="1" HorizontalAlignment="Right" VerticalAlignment="Top" Width="75" Margin="0,5,90,0"/>
<Button Grid.Row="3" Content="Storno" Grid.Column="1" HorizontalAlignment="Right" VerticalAlignment="Top" Width="75" Margin="0,5,10,0" Click="Button_Click"/>
</Grid>
I would like to, when I minimize NewMessage window, this window minimize to the bottom of MainWindow "taskbar". If you know gmail, there is the same principle. Any idea?
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);
}
I have a simple question about XAML.
I created a grid element inside another grid and added a textblock and a web browser in it. However, I am unable to access it in MainPage.xaml.cs using their name (e.g. this.LastName) doesn't work. On further debugging, I saw that they are not declared in MainPage.g.cs. Since MainPage.g.cs is auto defined, I don't know how to fix it. Can someone help please? Below is my C# and XAML code. Thanks!
========================================================
public partial class MainPage : Microsoft.Phone.Controls.PhoneApplicationPage {
internal System.Windows.Controls.Grid LayoutRoot;
internal System.Windows.Controls.Grid ContentPanel;
internal Microsoft.Phone.Controls.LongListSelector MainLongListSelector;
internal System.Windows.Controls.Image RefreshIcon;
private bool _contentLoaded;
/// <summary>
/// InitializeComponent
/// </summary>
[System.Diagnostics.DebuggerNonUserCodeAttribute()]
public void InitializeComponent() {
if (_contentLoaded) {
return;
}
_contentLoaded = true;
System.Windows.Application.LoadComponent(this, new System.Uri("/Suod;component/MainPage.xaml", System.UriKind.Relative));
this.LayoutRoot = ((System.Windows.Controls.Grid)(this.FindName("LayoutRoot")));
this.ContentPanel = ((System.Windows.Controls.Grid)(this.FindName("ContentPanel")));
this.MainLongListSelector = ((Microsoft.Phone.Controls.LongListSelector)(this.FindName("MainLongListSelector")));
this.RefreshIcon = ((System.Windows.Controls.Image)(this.FindName("RefreshIcon")));
}
}
========================================================
<Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
<phone:LongListSelector x:Name="MainLongListSelector" Margin="-12,-97,0,97" ItemsSource="{Binding Items}">
<phone:LongListSelector.ItemTemplate>
<DataTemplate>
<StackPanel Margin="12,100,0,45">
<Grid x:Name="CompanyContentGrid">
<Grid.RowDefinitions>
<RowDefinition Height="*"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<TextBlock Grid.Row="0" Name="LastName" Text="{Binding Name}" TextWrapping="Wrap" Margin="9,-7,0,0" Style="{StaticResource PhoneTextTitle1Style}"/>
<phone:WebBrowser Grid.Row="5" Height="400" Name="WebBrowser" Margin="12,-6,24,0" FontFamily="Portable User Interface"/>
</Grid>
</StackPanel>
</DataTemplate>
</phone:LongListSelector.ItemTemplate>
</phone:LongListSelector>
</Grid>
<Grid Grid.Row="2" >
<Image Source="/Assets/Refresh.png" Name="RefreshIcon" Width="80" Height="80" Tap="Image_Tap"/>
</Grid>
I think the problem is that your textblock i too deep in xaml code. I think Data Binding should be enough in this situation but there is a way to go around this problem. You have to subscribe this element to some event(like Loaded) and save sender to some property in code behind:
<TextBlock Loaded="LastName_Loaded" Grid.Row="0" Name="LastName" Text="{Binding Name}" TextWrapping="Wrap" Margin="9,-7,0,0" Style="{StaticResource PhoneTextTitle1Style}"/>
public TextBlock lastName;
private void LastName_Loaded(object sender, RoutedEventArgs e)
{
lastName= (TextBlock)sender;
}
Now you are able to access this element in code behind.