How to dynamically add key and value to the ResourceDictionary in wpf? - c#

<Application
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
x:Class="MultiLanguage.App"
StartupUri="MainWindow.xaml">
<Application.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary x:Name="LanguageDictionary" Source="/LanguageResources;component/EnglishResources.xaml"/>
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
</Application.Resources>
EnglishResources.xaml
<ResourceDictionary
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:sys="clr-namespace:System;assembly=mscorlib">
<sys:String x:Key="add">ADD</sys:String>
<sys:String x:Key="key">Key</sys:String>
<sys:String x:Key="stringValue">String Value</sys:String>
MainWindow.xaml
<Window
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
x:Class="MultiLanguage.MainWindow"
x:Name="Window"
Title="MainWindow"
Width="640" Height="480">
<Grid x:Name="LayoutRoot" HorizontalAlignment="Center" VerticalAlignment="Center">
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition Width="Auto"/>
</Grid.ColumnDefinitions>
<Button x:Name="btnAdd" Content="{DynamicResource add}" Height="48" Grid.Column="0" Grid.Row="3" Grid.ColumnSpan="2" Margin="10" Click="btnAdd_Click" />
<TextBlock Text="{DynamicResource key}" Height="40" Width="100" Grid.Column="0" Grid.Row="0" Margin="10"/>
<TextBlock Text="{DynamicResource stringValue}" Height="40" Width="100" Grid.Column="0" Grid.Row="1" Margin="10"/>
<TextBox x:Name="txtKey" Height="40" Width="200" Grid.Column="1" Grid.Row="0" Margin="10"/>
<TextBox x:Name="txtStringValue" Height="40" Width="200" Grid.Column="1" Grid.Row="1" Margin="10"/>
</Grid>
with above code, i get the following window
private void btnAdd_Click(object sender, RoutedEventArgs e)
{
AddKeyValue(txtKey.Text, txtStringValue.Text);
}
private void AddKeyValue(object key, object value)
{
// load the resource dictionary
var rd = new System.Windows.ResourceDictionary();
rd.Source = new System.Uri("pack://application:,,,/LanguageResources;component/EnglishResources.xaml", System.UriKind.RelativeOrAbsolute);
// add the new key with value
rd.Add(key, value);
// now you can save the changed resource dictionary
var settings = new System.Xml.XmlWriterSettings();
settings.Indent = true;
var writer = System.Xml.XmlWriter.Create(#"EnglishResources.xaml", settings);
System.Windows.Markup.XamlWriter.Save(rd, writer);
}
If i click Add button the value should be inserted in the resource dictionary which(EnglishResources.xaml) is already i have. But it is not insert. Please help me out.
I need Like
<ResourceDictionary
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:sys="clr-namespace:System;assembly=mscorlib">
<sys:String x:Key="add">ADD</sys:String>
<sys:String x:Key="key">Key</sys:String>
<sys:String x:Key="stringValue">String Value</sys:String>
<!-- the value should be inserted here. But not Insert-->
</ResourceDictionary>
After Added
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:s="clr-namespace:System;assembly=mscorlib">
<s:String x:Key="add">ADD</sys:String>
<s:String x:Key="key">Key</sys:String>
<s:String x:Key="stringValue">String Value</sys:String>
<!-- the value should be inserted here. But not Insert-->
</ResourceDictionary>
After i added the value into resource dictionary i get result like above. the sys is changed into to s and name space are merged as a line.

you can do it with this simple solution
private void AddKeyValue(object key, object value) {
// load the resource dictionary
var rd = new System.Windows.ResourceDictionary();
rd.Source = new System.Uri("pack://application:,,,/YOURAssemblyName;component/EnglishResources.xaml", System.UriKind.RelativeOrAbsolute);
// add the new key with value
//rd.Add(key, value);
if (rd.Contains(key)) {
rd[key] = value;
} else {
rd.Add(key, value);
}
// now you can save the changed resource dictionary
var settings = new System.Xml.XmlWriterSettings();
settings.Indent = true;
var writer = System.Xml.XmlWriter.Create(#"EnglishResources.xaml", settings);
System.Windows.Markup.XamlWriter.Save(rd, writer);
}
Usage
AddKeyValue("NewKey1", "StringValue");
AddKeyValue("NewKey2", 1000);
Hope that helps.

Related

WPF Mahapps Hamburger Menu open User Control with extended constructor

I'm using exactly this Hamburger menu example
https://jkarger.de/2017/02/06/mahapps-hamburgermenu/
This works fine as long the views have the default constructor.
However I need to pass an object from the MetroWindow, where the Hamburger menu is implemented, to a UserControl called by clicking a menu item.
The XAML code for the menu item is like this.
<controls:HamburgerMenu.ItemsSource>
<controls:HamburgerMenuItemCollection>
<controls:HamburgerMenuGlyphItem Glyph="" Label="Home">
<controls:HamburgerMenuGlyphItem.Tag>
<views:main />
</controls:HamburgerMenuGlyphItem.Tag>
</controls:HamburgerMenuGlyphItem>
<controls:HamburgerMenuGlyphItem Glyph="" Label="Private">
<controls:HamburgerMenuGlyphItem.Tag>
<views:private />
</controls:HamburgerMenuGlyphItem.Tag>
</controls:HamburgerMenuGlyphItem>
<controls:HamburgerMenuGlyphItem Glyph="" Label="Settings">
<controls:HamburgerMenuGlyphItem.Tag>
<views:settings />
</controls:HamburgerMenuGlyphItem.Tag>
</controls:HamburgerMenuGlyphItem>
</controls:HamburgerMenuItemCollection>
</controls:HamburgerMenu.ItemsSource>
For instance the "main" view.
<controls:HamburgerMenuGlyphItem.Tag>
<views:main />
</controls:HamburgerMenuGlyphItem.Tag>
This is the constructor of my "main" UserControl.
#region PUBLIC_PROPERTIES
TesterConfig.TesterConfig tc;
#endregion
public main(TesterConfig.TesterConfig configuration)
{
InitializeComponent();
tc = configuration;
}
XAML for the "main" UserControl"
<UserControl x:Class="TestsystemConfiguration.Views.main"
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:Controls="clr-namespace:MahApps.Metro.Controls;assembly=MahApps.Metro"
xmlns:local="clr-namespace:TestsystemConfiguration.Views"
mc:Ignorable="d"
d:DesignHeight="450" d:DesignWidth="800">
<Grid x:Name="gridMain">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="130"/>
<ColumnDefinition Width="423*"/>
<ColumnDefinition Width="175"/>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="70"/>
<RowDefinition Height="8"/>
<RowDefinition Height="36"/>
<RowDefinition Height="36"/>
<RowDefinition Height="36"/>
<RowDefinition Height="11*"/>
<RowDefinition Height="45*"/>
<RowDefinition Height="40"/>
</Grid.RowDefinitions>
<Image x:Name="imageLogo" Grid.Column="2" Source="pack://siteoforigin:,,,/Resources/logo.png" Margin="5" Grid.RowSpan="1"/>
<ComboBox x:Name="cbWorkingStation" IsEnabled="False" Grid.Column="1" Margin="5,2,10,2" Grid.Row="2" SelectionChanged="cbWorkingStation_SelectionChanged"/>
<Button x:Name="btnOpenDocs" Content="Doku öffnen" Style="{StaticResource AccentedSquareButtonStyle}" Grid.Column="2" Margin="5" Grid.Row="7" Controls:ControlsHelper.ContentCharacterCasing="Upper"/>
<Label Content="Arbeitsplatz:" Grid.Row="2" FontWeight="Bold"/>
</Grid>
</UserControl>
The "TesterConfig" is an object in my project and declared in the parent MetroWindow. How can I pass the reference to the UserControl?
Thanks for your help!
Thanks #mm8.
According to your suggestions I did it this way.
XAML (MenuItem)
<Controls:HamburgerMenuGlyphItem Glyph=""
Label="Home"
Tag="main">
</Controls:HamburgerMenuGlyphItem>
C# Code:
private void MenuControl_ItemClick(object sender, ItemClickEventArgs e)
{
HamburgerMenuGlyphItem i = e.ClickedItem as HamburgerMenuGlyphItem;
if(i != null)
{
UserControl uc = new UserControl();
switch(i.Tag.ToString())
{
case "main":
uc = new Views.main(tc);
break;
case "testsystems":
uc = new Views.testsystems();
break;
}
i.Tag = uc;
this.MenuControl.Content = i;
}
}
I created a switch depending on the tag.
Thanks for your help!
Best,
Andy

RDLC report not showing up inside a user control

I am trying to show a rdlc report inside a user control. The problem is that it does not show when I run the project.
Before running the project I can see it in xaml designer.
After Running project:
Here is my code:
Report User Control:
<UserControl x:Class="CPOSApplication.UserControls.Reports.ReportViewer"
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="300" Background="#FFFFFFFF"
xmlns:repview="clr-namespace:Microsoft.Reporting.WinForms;assembly=Microsoft.ReportViewer.WinForms">
<Grid>
<WindowsFormsHost x:Name="winform" Background="White" Visibility="Visible">
<repview:ReportViewer BackColor="white" x:Name="salesReportViewer"/>
</WindowsFormsHost>
</Grid>
Another UserControl where it is being used:
<UserControl x:Class="CPOSApplication.UserControls.Reports.SalesReport"
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:uc="clr-namespace:CPOSApplication.UserControls.Reports"
mc:Ignorable="d"
d:DesignHeight="800" d:DesignWidth="900">
<Grid Style="{DynamicResource GridsCustomStyle}" x:Name="SearchShelfGri">
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="*" />
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
<ColumnDefinition MinWidth="100" />
</Grid.ColumnDefinitions>
<Border Grid.ColumnSpan="2" Style="{DynamicResource SearchGridHeaderBorder}">
<DockPanel Grid.Row="0">
<Label x:Name="GridLabel" Style="{DynamicResource HeadingLabelsCustomStyle}" Content="Sales Report-:"/>
</DockPanel>
</Border>
<uc:ReportViewer x:Name="salesReport" Grid.Column="0" Background="White" Grid.Row="1" Margin="0,0"/>
<uc:FilterSalesReport x:Name="filterShelf" Grid.Column="1" Grid.Row="1" Background="AliceBlue" Width="300" Padding="2,0,0,0" Margin="0,0"/>
</Grid>
It's .cs File
public partial class SalesReport : UserControl
{
public SalesReport()
{
InitializeComponent();
salesReport.salesReportViewer.ProcessingMode = ProcessingMode.Local;
salesReport.salesReportViewer.LocalReport.ReportPath = #"C:\Users\Safi\Documents\Visual Studio 2012\Projects\CPOS\CPOS\CPOSApplication\Reports\QuarterSaleInvoiceReport.rdlc";
salesReport.salesReportViewer.RefreshReport();
salesReport.salesReportViewer.LocalReport.ReportEmbeddedResource = "CPOSApplication.Reports." + ReportType.QuarterSaleInvoice.ToString() + "Report.rdlc";
salesReport.salesReportViewer.RefreshReport();
}
}
//in your CS file, create this method
public void GenReport()
{
YourReportViewfname.LocalReport.ReportPath = #"paste Your RDLC Location";
YourClass rptclsProp01 = new YourClass();
var data = rptclsProp01.YourList();
ReportDataSource dataSource = new ReportDataSource("YourDataSet", data);
YourReportViewfname.LocalReport.DataSources.Clear();
YourReportViewfname.LocalReport.DataSources.Add(dataSource);
YourReportViewfname.RefreshReport();
YourReportViewfname.Show();
}
//then Button Click event, just call the method
this.YourUCfnam.salesReport.GenReport();
//hope that report will show

Geolocator.PositionChanged event gets raises when I try GeoLocator.GetPositionAsync()

So, I'm getting some weird behavior when getting the current position using the GetPositionAsync method in my app. It seems to be firing the PositionChanged event when I query for the position. I'm not sure exactly what's going on and it's hard to debug since the call is asynchronous. Here's some sample code that illustrates the problem, (you'll need a Bing Maps key to test it):
MainPage.xaml.cs
using System;
using Bing.Maps;
using Windows.UI.Xaml.Input;
using Windows.Devices.Geolocation;
using Windows.UI.Core;
using GeoPositionExercise.Model;
namespace GeoPositionExercise
{
public sealed partial class MainPage
{
private Geolocator _geolocator;
private LocationIcon _locationIcon = new LocationIcon();
public MainPage()
{
InitializeComponent();
MyMap.Children.Add(_locationIcon);
_geolocator = new Geolocator();
//LoadPoly(PolyLayer, DefaultStyle, GetLocation);
_geolocator.PositionChanged += this._geolocator_PositionChanged;
}
private void _geolocator_PositionChanged(Geolocator sender, PositionChangedEventArgs args)
{
this.Dispatcher.RunAsync(CoreDispatcherPriority.Low, new DispatchedHandler(
() =>
{
displayPosition(this, args.Position.Coordinate);
}));
}
private void displayPosition(object sender, Geocoordinate coordinate)
{
Location location = new Location(coordinate.Latitude, coordinate.Longitude);
MapLayer.SetPosition(_locationIcon, location);
MyMap.SetView(location, 15.0f);
}
private async void GetLocation(object sender, TappedRoutedEventArgs e)
{
// This raises a PositionChanged event for some reason
var position = await _geolocator.GetGeopositionAsync();
}
}
}
MainPage.xaml
<common:PageBase 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:interactivity="using:Microsoft.Xaml.Interactivity"
xmlns:common="using:GeoPositionExercise.Common"
xmlns:local="using:GeoPositionExercise"
xmlns:ignore="http://www.ignore.com"
x:Name="PageRoot"
x:Class="GeoPositionExercise.MainPage"
xmlns:m="using:Bing.Maps"
mc:Ignorable="d ignore"
DataContext="{Binding Main, Source={StaticResource Locator}}">
<Page.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="Skins/MainSkin.xaml" />
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
</Page.Resources>
<Page.BottomAppBar>
<AppBar>
<AppBarButton Label="Get Location" Tapped="GetLocation">
<AppBarButton.Icon>
<FontIcon Glyph="" />
</AppBarButton.Icon>
</AppBarButton>
</AppBar>
</Page.BottomAppBar>
<Grid x:Name="MainGrid" Background="{StaticResource ApplicationPageBackgroundThemeBrush}" Margin="0,0,0,53">
<m:Map x:Name="MyMap" Credentials="YOUR BING MAP KEY HERE" >
<m:MapLayer x:Name="PinLayer"/>
<m:MapLayer x:Name="InfoboxLayer" Visibility="Collapsed">
<Grid x:Name="Infobox" Width="350">
<Border Background="Black" Opacity="0.8" BorderBrush="White" BorderThickness="2" CornerRadius="5"/>
<Grid Margin="5">
<StackPanel HorizontalAlignment="Left" Margin="10">
<TextBlock x:Name="InfoboxTitle" FontSize="18" Width="290" HorizontalAlignment="Left" TextWrapping="Wrap" />
<WebView x:Name="InfoboxDescription" Width="330" Height="100" Margin="0,10,0,0"/>
</StackPanel>
</Grid>
</Grid>
</m:MapLayer>
</m:Map>
</Grid>
</common:PageBase>
And finally a user control LocationIcon:
<UserControl
x:Class="GeoPositionExercise.Model.LocationIcon"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:GeoPositionExercise.Model"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
d:DesignHeight="300"
d:DesignWidth="400">
<Canvas>
<Ellipse Height="25" Width="25" Fill="#FFF0F0F0" Margin="-12.5,-12.5,0,0"></Ellipse>
<Ellipse Height="20" Width="20" Fill="Black" Margin="-10,-10,0,0"></Ellipse>
<Ellipse Height="10" Width="10" Fill="White" Margin="-5,-5,0,0"></Ellipse>
</Canvas>
</UserControl>
Make sure to have the right references and target a X64 or x82 platform before compiling. You can test this by clicking the "Get Location" app bar button, it'll always center the map at the current location. I'm not really sure why this is occuring, since the only place I call displayPosition is in the _geolocator_PostionChanged method.

Dynamically adding contents to stackpanel in code behind

Am trying to add Set of labels and images in a stackpanel in code behind.And finally am attaching that stackpanel to particular column of a grid control.My expected output should be like
<image><label>
combination
but my output is like it displays the label in first column of grid and the image in the next column.(I was not able to add the snapshots since i dont have enough reputations)
XAML code
<Window x:Class="Ping.MainWindow" WindowStyle="ThreeDBorderWindow" Icon="F:\ChatApplication\Ping\Ping\Images\title.ico" Cursor="Pen"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Ping - Connected by alphabets" Height="450" Width="750" WindowStartupLocation="CenterScreen" SizeToContent="WidthAndHeight" >
<Grid Name="grid_window">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="200"/>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<GridSplitter HorizontalAlignment="Right"
VerticalAlignment="Stretch"
Grid.Column="1" ResizeBehavior="PreviousAndNext"
Width="5" Background="#FFBCBCBC"/>
<TabControl Grid.ColumnSpan="2" Name="tab_control" BorderBrush="Cornsilk" BorderThickness="4" HorizontalAlignment="Left" Height="419" Margin="227,0,0,0" VerticalAlignment="Top" Width="515">
<TabItem Header="Home" BorderBrush="Green"/>
</TabControl>
</Grid>
code behind
public MainWindow()
{
InitializeComponent();
DBCoding dbobj = new DBCoding();
//Contains names {"Dhivi","Walle"}
List<string> online = new List<string>();
online = dbobj.onlineUsers();
StackPanel myStackPanel = new StackPanel();
myStackPanel.Orientation = Orientation.Vertical;
foreach (var item in online)
{
Image myImage = new Image();
myImage.Source = new BitmapImage(new Uri("F:\\ChatApplication\\Ping\\Ping\\Images\\visible.png"));
myImage.Width = 10;
myImage.Height = 10;
//myImage.Margin = new Thickness(-10,0,-80,0);
myImage.Height = 10;
Label user = new Label();
user.Content = item.ToString();
myStackPanel.Children.Add(myImage);
myStackPanel.Children.Add(user);
}
grid_window.Children.Add(myStackPanel);
Grid.SetColumnSpan(myStackPanel, 1);
Grid.SetColumn(myStackPanel, 0);
}
Can anybody tell me the solution.
Here's how your code should look like, using data binding, an ItemsControl and a DataTemplate:
XAML
<Window x:Class="Ping.MainWindow" WindowStyle="ThreeDBorderWindow" Icon="F:\ChatApplication\Ping\Ping\Images\title.ico" Cursor="Pen"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Ping - Connected by alphabets" Height="450" Width="750" WindowStartupLocation="CenterScreen" SizeToContent="WidthAndHeight" >
<Grid Name="grid_window">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="200"/>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<GridSplitter HorizontalAlignment="Right"
VerticalAlignment="Stretch"
Grid.Column="1" ResizeBehavior="PreviousAndNext"
Width="5" Background="#FFBCBCBC"/>
<TabControl Grid.ColumnSpan="2" Name="tab_control" BorderBrush="Cornsilk" BorderThickness="4" HorizontalAlignment="Left" Height="419" Margin="227,0,0,0" VerticalAlignment="Top" Width="515">
<TabItem Header="Home" BorderBrush="Green"/>
</TabControl>
<ItemsControl ItemsSource="{Binding}">
<ItemsControl.ItemTemplate>
<DataTemplate>
<DockPanel>
<!-- You really should add the image as a resource to the project -->
<Image Source="F:\ChatApplication\Ping\Ping\Images\visible.png"
Width="10" Height="10" />
<TextBlock Text="{Binding}" />
</DockPanel>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</Grid>
C#
public MainWindow()
{
InitializeComponent();
DBCoding dbobj = new DBCoding();
List<string> online = dbobj.onlineUsers();
DataContext = online;
}

UserControl with changing content template for displaying content

I have a situation in which i need to create a user control that hosts a content presenter. Now, the content presenter should be using the template to display data.
I have designed a user control as follows. xaml
<UserControl x:Class="Dashboard.ComponentStatisticsControl"
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"
Name="SatisticsControl"
mc:Ignorable="d"
d:DesignHeight="300" d:DesignWidth="300">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<Label Content="{Binding ElementName=SatisticsControl, Path=Title}"
Grid.Row="0"
Background="SkyBlue"/>
<ContentPresenter Content="{Binding ElementName=SatisticsControl, Path=AdditionalContent}"
Grid.Row="1"/>
</Grid>
</UserControl>
Now i have a WrapPanel defined in my MainWindow.xaml that should host the ComponentStatisticsControl
<Window x:Class="Dashboard.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:Dashboard"
Height="350" Width="525"
ShowInTaskbar="True"
WindowState="Maximized"
WindowStyle="None"
Name="_this">
<Window.Resources>
<LinearGradientBrush x:Key="PanelBackground"
StartPoint="0, 1"
EndPoint="1, 0">
<GradientStop Color="SkyBlue" Offset="0.3"/>
<GradientStop Color="PaleGreen" Offset="1"/>
</LinearGradientBrush>
<SolidColorBrush x:Key="BorderBrush"
Color="Blue"/>
</Window.Resources>
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
<StackPanel Grid.Row="0">
<Button Click="Button_Click"
HorizontalAlignment="Left"
VerticalAlignment="Center">Click</Button>
</StackPanel>
<WrapPanel Name="WrapPanelMain"
Orientation="Horizontal"
FlowDirection="LeftToRight"
Grid.Row="1">
</WrapPanel>
</Grid>
</Window>
Now i am creating the content for the ComponentStatisticsControl in code behind.
public void CreateComponent(ref DiscoveryMessage Message)
{
switch (Message.Identifier)
{
case ComponentIdentifier.Dispatcher:
{
ComponentStatisticsControl StatisticsControl = new ComponentStatisticsControl();
StatisticsControl.Title = "Dispatcher";
StatisticsControl.AdditionalContent = new Label() { Content = "Hello"};
WrapPanelMain.Children.Add(StatisticsControl);
break;
}
}
}
However, i can not see the data added. What did i miss out. I have spent much time banging about what went wrong.
I should be able to see the content set for the label "Hello" in the WrapPanel.
public class DispatcherStatistics
{
private uint f_QCount;
public uint QueueCount { get { return f_QCount; }
set
{
f_QCount = value;
}
}
}
I will be setting this class instance to the AdditionalContent. So that QueueCount will be updated whenever i assign a new instance of this class.
Thanks in advance
EDIT
I was getting the text of my class type in the wrap panel. Now the above problem is solved, but how can i define a template for the content to show.
public void CreateComponent(ref DiscoveryMessage Message)
{
1switch (Message.Identifier)
{
case ComponentIdentifier.Dispatcher:
{
ComponentStatisticsControl StatisticsControl = new ComponentStatisticsControl();
StatisticsControl.Title = "Dispatcher";
StatisticsControl.AdditionalContent = f_clDispatcherStatistics;
WrapPanelMain.Children.Add(StatisticsControl);
break;
}
}
}
f_clDispatcherStatistics is a private instance variable for DispatcherStatistics class
This is displaying "Dashboard.DispatcherStatistics"
I want to display something like
QueueCount : 0
like this format.
You are doing it a little complicated. You can use the Content property of UserControl directly.
Here is the important part of the template (using the default ContentPresenter):
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<Label Content="{Binding ElementName=SatisticsControl, Path=Title}"
Grid.Row="0"
Background="SkyBlue"/>
<ContentPresenter Grid.Row="1"/>
</Grid>
And then use the Content property directly:
ComponentStatisticsControl StatisticsControl = new ComponentStatisticsControl();
StatisticsControl.Title = "Dispatcher";
StatisticsControl.Content = new Label() { Content = "Hello"};
WrapPanelMain.Children.Add(StatisticsControl);

Categories

Resources