Image not displaying in UserControl - c#

I've found so many answers to this questions, but no matter what I try nothing seems to work.
I'm trying to create a UserControl in a UWP Application. The User Control consists of a Border, with an Image and a TextBlock inside of it. I managed to get the TextBlock text to show up, but no matter what I do I can't seem to get an Image to display in the UserControl.
Things tried so far:
Changing GraphicProperty typeof to Image, ImageSource, and Uri.
Placing the Image in the Border into a ContentPresenter.
Other things I can't remember at this point.
I'm at a loss as to how to get this to work. I know I've done this before, but it was several years ago and I've apparently fogotten how (or something significant changed with UWP, as most of my experience is in WPF).
Could someone please help find where I'm messing this up?
UserControl XAML:
<UserControl
x:Class="ShirtSleeves.CardControlxaml"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:ShirtSleeves"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
x:Name="CardControl"
mc:Ignorable="d"
d:DesignHeight="400"
d:DesignWidth="300">
<Grid>
<Border Margin="0,10" Background="White" BorderBrush="Black" BorderThickness="5" Width="260" Height="352" CornerRadius="20">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<Image Source="{Binding ElementName=CardControl, Path=Graphic}" Height="200" Width="200" HorizontalAlignment="Center" VerticalAlignment="Bottom" />
<TextBlock Text="{Binding ElementName=CardControl, Path=Label}" Grid.Row="1" HorizontalAlignment="Center" VerticalAlignment="Top" Margin="0,30" Foreground="Black" FontSize="48" FontWeight="Bold" />
</Grid>
</Border>
</Grid>
</UserControl>
UserControl C#:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
// The User Control item template is documented at https://go.microsoft.com/fwlink/?LinkId=234236
namespace ShirtSleeves
{
public sealed partial class CardControlxaml : UserControl
{
//private TextBlock label;
public static DependencyProperty LabelProperty = DependencyProperty.Register("Label", typeof(string),
typeof(CardControlxaml), new PropertyMetadata("Label"));
public static DependencyProperty GraphicProperty = DependencyProperty.Register("Graphic", typeof(string),
typeof(CardControlxaml), new PropertyMetadata(null));
public string Label
{
get { return (string)GetValue(LabelProperty); }
set { SetValue(LabelProperty, value); }
}
public string Graphic
{
get { return (string)GetValue(GraphicProperty); }
set { SetValue(GraphicProperty, value); }
}
public CardControlxaml()
{
this.InitializeComponent();
}
}
}
MainPage XAML:
<Page
x:Class="ShirtSleeves.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:ShirtSleeves"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
d:DesignHeight="1200"
Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
<Grid Background="DarkGreen">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
<ColumnDefinition Width="3*" />
</Grid.ColumnDefinitions>
<ScrollViewer Grid.Column="0">
<StackPanel>
<Border Margin="0,10" Background="White" BorderBrush="Black" BorderThickness="5" Width="260" Height="352" CornerRadius="20">
<TextBlock Text="Games" HorizontalAlignment="Center" VerticalAlignment="Bottom" Margin="0,30" Foreground="Black" FontSize="48" FontWeight="Bold" />
</Border>
<Border Margin="0,10" Background="White" BorderBrush="Black" BorderThickness="5" Width="260" Height="352" CornerRadius="20">
<TextBlock Text="Sleeves" HorizontalAlignment="Center" VerticalAlignment="Bottom" Margin="0,30" Foreground="Black" FontSize="48" FontWeight="Bold" />
</Border>
<local:CardControlxaml Label="Search" Graphic="C:\Users\<username>\source\repos\ShirtSleeves\ShirtSleeves\Images\Rook (Games).png" Foreground="Black" />
<Image Height="250" Source="C:\\Users\\<username>\\source\\repos\\ShirtSleeves\\ShirtSleeves\\Images\\Rook (Games).png" HorizontalAlignment="Center" VerticalAlignment="Center" />
</StackPanel>
</ScrollViewer>
<Viewbox Grid.Column="1">
<Image Source="C:\Users\<username>\source\repos\ShirtSleeves\ShirtSleeves\Images\Rook (Games).png" VerticalAlignment="Top" HorizontalAlignment="Center" />
</Viewbox>
</Grid>
</Page>

UWP doesn't allow to access files outside the app container directly. This means that you could not set the image source like this C:\Users\<username>\source\repos\ShirtSleeves\ShirtSleeves\Images\Rook (Games).png.
In your case, the simplest way is to put the image into your project's Assets folder like the following:
Then, you could specify the 'Graphic' property like this:
<local:CardControlxaml Label="Search" Graphic="Assets/animals.jpg" Foreground="Black" />
More information, please read File access permissions.

Related

C# WPF Prism RegionManager failed to navigate

Using WPF .Net Core 3.1 + Prism.
I've implemented TabControl with dynamically added TabItems.
RegionManager works just fine when trying to navigate to region within MainWindow, but it failed when trying to navigate to region whithin the TabPage. Does not work neither from MainWindowViewModel, nor from TabPageViewModel.
Project's repo may be found here: GitHub.
MainWindow.xaml:
<TabControl Margin="10" ItemsSource="{Binding TabPages, UpdateSourceTrigger=PropertyChanged}">
<TabControl.Resources>
<DataTemplate DataType="{x:Type viewmodels:SomeTabPageViewModel}">
<views:SomeTabPage/>
</DataTemplate>
</TabControl.Resources>
<TabControl.ItemTemplate>
<DataTemplate DataType="{x:Type interfaces:ITabPage}" x:Name="dt">
<Grid VerticalAlignment="Stretch" HorizontalAlignment="Stretch" Height="40">
<TextBlock Grid.Column="1" Margin="5,10,10,10" Text="{Binding TabName}" TextAlignment="Center" VerticalAlignment="Center" FontSize="16"/>
</Grid>
</DataTemplate>
</TabControl.ItemTemplate>
</TabControl>
SomeTabPage.xaml:
<UserControl x:Class="WpfPrismRegionFailure.Views.SomeTabPage"
xmlns:prism="http://prismlibrary.com/"
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">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="50"/>
<RowDefinition Height="Auto"/>
<RowDefinition/>
</Grid.RowDefinitions>
<Button Grid.Row="0" Content="Navigate From Inside Of TabPage (not working)" Command="{Binding NavigateFromInsideOfTabPageCommand}" FontSize="16" Background="Orange"/>
<TextBlock Grid.Row="1" Margin="10,20,0,0" Text="The area below contains region 'RegionInsideTabPage', but can't navigate to it." FontSize="16"/>
<Border Grid.Row="2" BorderBrush="Orange" BorderThickness="2" CornerRadius="10" Margin="10">
<ContentControl Margin="10" prism:RegionManager.RegionName="RegionInsideTabPage"/>
</Border>
</Grid>
</UserControl>
SomeTabPageViewModel.cs:
using Prism.Commands;
using Prism.Ioc;
using Prism.Regions;
using System.Windows.Input;
using WpfPrismRegionFailure.Base;
namespace WpfPrismRegionFailure.ViewModels
{
public class SomeTabPageViewModel : TabPageBase
{
public SomeTabPageViewModel(IContainerProvider containerProvider) : base(containerProvider)
{
this.NavigateFromInsideOfTabPageCommand = new DelegateCommand(OnNavigateFromInsideOfTabPage);
}
public SomeTabPageViewModel(IRegionManager regionManager) : base (regionManager)
{
this.NavigateFromInsideOfTabPageCommand = new DelegateCommand(OnNavigateFromInsideOfTabPage);
}
public ICommand NavigateFromInsideOfTabPageCommand { get; }
private void OnNavigateFromInsideOfTabPage()
{
System.Diagnostics.Trace.WriteLine($"SomeTabPageViewModel _regionManager ContainsRegionWithName RegionInsideTabPage: {this._regionManager.Regions.ContainsRegionWithName("RegionInsideTabPage")}");
this._regionManager.RequestNavigate("RegionInsideTabPage", "RegionContent");
}
}
}
Inside of TabPageViewModel regionManager.Regions.ContainsRegionWithName("RegionInsideTabPage") returns 'false' despite of the region is being declared in XAML
<ContentControl Margin="10" prism:RegionManager.RegionName="RegionInsideTabPage"/>
Project's repo may be found here: GitHub.
Someone heeeeeeelp me please

Accessing/Setting Custom Text Properties of codebehind through XAML

Having some trouble getting my head around all the DP's i've recreated a very simple version of of my problem to try and sort out what the issue is. Alas, im still stumped..
I Have a custom userControl, and am attempting to set the properties of a textblock through the page that is instantiating that control. At the moment, in this version below, as a means of teaching myself im only trying to access a property from code behind.
The reason I wish to set custom text properties etc. is because I wish to have multiple versions of the control on the page with custom behaviour/text etc.
Here is my code behind.
public partial class FeedbackCtrl : UserControl
{
public bool IsFlagSet
{
get { return (bool)GetValue(IsFlagSetProperty); }
set { SetValue(IsFlagSetProperty, value); }
}
public static readonly DependencyProperty IsFlagSetProperty =
DependencyProperty.Register("IsFlagSet", typeof(bool), typeof(FeedbackCtrl), new PropertyMetadata(false));
public FeedbackCtrl()
{
InitializeComponent();
this.DataContext = this;
}
}
And my XAML..
<UserControl x:Class="Pipeline_General.Custom_Controls.FeedbackCtrl" x:Name="ThisCtrl"
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"
d:DesignHeight="300" d:DesignWidth="300">
<Grid>
<Expander HorizontalAlignment="Stretch" >
<Expander.Header Name="Header">
<Grid HorizontalAlignment="Stretch" Width="NaN">
<Border Background="Transparent" HorizontalAlignment="Stretch" BorderBrush="gray" BorderThickness="0,0,0,1"
Width="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type Expander}}, Path=ActualWidth}">
<TextBlock Foreground="#FFFF72D2" Text="{Binding Path=IsFlagSet}">
</TextBlock>
</Border>
</Grid>
</Expander.Header>
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="30" />
<RowDefinition Height="*" />
</Grid.RowDefinitions>
<ScrollViewer Grid.Row="1">
<StackPanel Orientation="Vertical" VerticalAlignment="Top" Margin="5"/>
</ScrollViewer>
</Grid>
</Expander>
</Grid>

WPF Border shape

I want to create a popup like the one that Lync 2013 has:
What I´m interested in, is to create a control with that vignette shape.
I have tried creating a UserControl with a Canvas inside and a Path with the shape. But I was not finding Canvas very friendly, so I was wondering if I can achieve this by "playing" with the Border control, so as to put only a border and then a grid inside.
Is this possible? Can somebody help me to be in the right track?
This is my XAML:
<Window x:Class="CustomBorderStyle.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
LocationChanged="Window_LocationChanged"
Title="MainWindow" Height="350" Width="525">
<Grid>
<Border BorderBrush="Silver" BorderThickness="1">
<Button Content="Nice image button" Name="btnThingToClick" Width="100" Height="100" Click="btnThingToClick_Click" />
</Border>
<Popup Name="myPopup"
AllowsTransparency="True"
PlacementTarget ="{Binding ElementName=btnThingToClick}"
Placement="Custom">
<Grid x:Name="grid" Height="200" Width="200" Background="Transparent">
<Grid.RowDefinitions>
<RowDefinition Height="*"/>
<RowDefinition Height="40"/>
</Grid.RowDefinitions>
<Border BorderBrush="Silver" BorderThickness="1" Background="White" CornerRadius="5" Grid.Row="0" Padding="5">
<StackPanel Orientation="Vertical">
<TextBlock Text="Some stuff" />
<Button Content="Click me" Width="50" />
</StackPanel>
</Border>
<Path Fill="White" Stretch="Fill" Stroke="Silver" HorizontalAlignment="Left" Margin="30,-1.6,0,0" Width="25" Grid.Row="1"
Data="M22.166642,154.45381 L29.999666,187.66699 40.791059,154.54395"/>
</Grid>
</Popup>
</Grid>
</Window>
This is my code behind for the main window:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Windows.Controls.Primitives;
namespace CustomBorderStyle
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
//wire up the popup to the popup placement method
myPopup.CustomPopupPlacementCallback = new CustomPopupPlacementCallback(placePopup);
}
private void btnThingToClick_Click(object sender, RoutedEventArgs e)
{
//just invert if it's open or not
myPopup.IsOpen = !myPopup.IsOpen;
}
//this is to position the popup next to the button
public CustomPopupPlacement[] placePopup(Size popupSize,
Size targetSize,
Point offset)
{
CustomPopupPlacement placement1 =
new CustomPopupPlacement(new Point(10, -200), PopupPrimaryAxis.Vertical);
CustomPopupPlacement placement2 =
new CustomPopupPlacement(new Point(10, 20), PopupPrimaryAxis.Horizontal);
CustomPopupPlacement[] ttplaces =
new CustomPopupPlacement[] { placement1, placement2 };
return ttplaces;
}
private void Window_LocationChanged(object sender, System.EventArgs e)
{
//if the popup is open when the window's location changes
if (myPopup.IsOpen)
{
//toggle the popup to redraw the location
myPopup.IsOpen = false;
myPopup.IsOpen = true;
}
}
}
}
You will obviously need some nice images to use for the buttons and some better stuff to put in the stackpanel so the popup looks nice, but that should do the job :)
The thing you have to be careful with is the positioning of the popup, this means if you change the height of the popup by adding more stuff you need to change the values of the "CustomPopupPlacement" objects, there might be a nice way to fix this??
I just wanted to paste some code that works for me:
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="Auto" />
</Grid.ColumnDefinitions>
<Popup Placement="Top"
IsOpen="{Binding SettingsVisible}"
PopupAnimation="Fade"
AllowsTransparency="True">
<Grid Background="Transparent">
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
<Border Grid.Row="0" CornerRadius="10" Background="SkyBlue" HorizontalAlignment="Left">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto"></RowDefinition>
<RowDefinition Height="Auto"></RowDefinition>
</Grid.RowDefinitions>
<TextBlock Grid.Row="0">Hello, world</TextBlock>
<Button Grid.Row="1">Click Me!</Button>
</Grid>
</Border>
<Path Grid.Row="1" VerticalAlignment="Bottom" Data="M 10 0 L 20 10 L 30 0 Z" Fill="SkyBlue" />
</Grid>
</Popup>
<Button Grid.Column="0" HorizontalAlignment="Left" Command="{Binding ToggleSettingsVisibility}">Settings</Button>
<Button x:Uid="Button_1" IsEnabled="{Binding SettingsVisible}" Grid.Column="1" HorizontalAlignment="Right" Padding="30, 10" Command="{Binding Next}">Next</Button>
</Grid>
My example features two buttons, important for this example is the 1st one (it is part of a wizard-like UI, but you can ignore the 2nd button).
I don't have the ViewModel here, but the mechanism is simple, the Settings-Button binds against the property ToggleSettingsVisibility which sets the SettingsVisibility the Popup binds against. All that is not really important for the example.
The result looks like this:
Of course, I still have to work on the styling ;-)

How to place an XAML usercontrol in a grid

I have the following main.xaml and usercontrol.
I need to place several times the user control on the 2nd row, 2nd column of the grid, By using visual studio it wont allow to drag and drop the user control, so I suppose I have to do it by code, I just dont know how
MainPage.xaml
<Grid HorizontalAlignment="Left" Height="768" VerticalAlignment="Top" Width="1366" x:Name="grid" Background="Black">
<Grid.RowDefinitions>
<RowDefinition Height="150"/>
<RowDefinition/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition/>
<ColumnDefinition Width="250"/>
</Grid.ColumnDefinitions>
<Border BorderBrush="White" BorderThickness="3" Grid.Column="1" Background="Red" CornerRadius="30"/>
<TextBlock x:Name="txtCountry" Grid.Column="1" TextWrapping="Wrap" FontSize="36" HorizontalAlignment="Center" VerticalAlignment="Center"/>
<TextBlock x:Name="txtTime" Grid.Row="1" TextWrapping="Wrap" FontSize="180" HorizontalAlignment="Center" VerticalAlignment="Center"/>
</Grid>
Usercontrol
<UserControl
x:Class="AlarmPro.TimeOnCity"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:AlarmPro"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
d:DesignHeight="150"
d:DesignWidth="250">
<Grid Background="Black">
<Grid.RowDefinitions>
<RowDefinition Height="30"/>
<RowDefinition/>
</Grid.RowDefinitions>
<Border BorderBrush="#FFDE6A6A" BorderThickness="1" Grid.Row="0" Grid.Column="0" Background="#FFDC4646">
<TextBlock TextWrapping="Wrap" Text="TextBlock" HorizontalAlignment="Center" VerticalAlignment="Center" FontSize="16"/>
</Border>
<Border BorderBrush="Black" BorderThickness="1" Grid.Row="1" Background="#FFAE4F00">
<TextBlock TextWrapping="Wrap" Text="TextBlock" HorizontalAlignment="Center" VerticalAlignment="Center" FontSize="36"/>
</Border>
</Grid>
</UserControl>
Do you mean like this?
<my:UserControlName Grid.Column="2" Grid.Row="2" ... />
<my: in this case is the alias for the CLR namespace the UserControl resides in. It is defined at the top of your XAML, inside the <Window> or <UserControl> tag depending on context.
For example,
<Window ...
xmlns:my="clr-namespace:AssemblyName"
...
/>
MainPage.Xaml
<Page
x:Class="UserControlExample.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:UserControlExample"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d">
<Grid x:Name="MainContent" Background="Azure" >
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<ScrollViewer Grid.Row="1" HorizontalScrollBarVisibility="Hidden"
VerticalScrollBarVisibility="Hidden">
<local:UserControl1 x:Name="MyHelloWorldUserControl" Grid.Row="1" />
</ScrollViewer>
</Grid>
</Page>
UserControl1.xaml
<UserControl
x:Class="UserControlExample.UserControl1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:UserControlExample"
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">
<Grid Background="Bisque">
<StackPanel>
<StackPanel Orientation="Horizontal" Height="81">
<TextBlock Text="Your Name is" Foreground="Blue" FontSize="30" Margin="0,0,0,10"/>
<TextBox x:Name="Input" Background="White" Width="225" />
</StackPanel>
<Button Content="Click Me" Foreground="Brown" FontSize="30" Click="Button_Click"/>
<TextBlock x:Name="Output" FontSize="100"/>
</StackPanel>
</Grid>
</UserControl>
MainPage.xaml, I am binding a login UserControl
by using the namespace : xmlns:UC="clr-namespace:Test.Views" , since I have my usercontrol in Folder named "Views".
<ScrollViewer>
<UC:Login BtnLoginClick="Login_BtnLoginClick"/>
</ScrollViewer>
Login.cs
public partial class Login : UserControl {
public event EventHandler BtnLoginClick;
public Login()
{
InitializeComponent();
}
private void btnLogin_Click(object sender, RoutedEventArgs e)
{
string userName = txtUserName.Text;
string userPassword = txtUserPassword.Password.Trim();
if (userName != null && userName != string.Empty && userPassword != null && userPassword != string.Empty)
{
if (this.BtnLoginClick != null)
{
this.BtnLoginClick(this, e);
}
}
else
{
MessageBox.Show("Invalid username or password");
}
}
}
Finally, dont forgot to use the event handler in MainPage.xaml to capture the button clicked event from Login Usercontrol to do other actions.
MainPage.xaml
<UC:Login BtnLoginClick="Login_BtnLoginClick"/>
Here "BtnLoginClick" its an event Handler defined in the Login.xaml[User Control].
Create new event for this "BtnLoginClick" event as i created "Login_BtnLoginClick".
MainPage.cs
private void Login_BtnLoginClick(object sender, EventArgs e)
{
Messagebox.Show("Event captured successfully");
////Here you can add your stuffs...
}
For UWP, in UserControl.xaml, find the local namespace xmlns:local notation: xmlns:local="using:ProjectName.Folder" at the top (by convention, C# namespaces are named the same way as the folder that contains them, so folder also means namespace).
In MainPage.xaml, add a reference to this namespace. The reference prefix can be any name desired: for example, CustomPrefix, as in xmlns:CustomPrefix="using:ProjectName.Folder". Then, anywhere in MainPage.xaml, display the control by prefixing its name with <CustomPrefix:...>.
UserControl.xaml
<UserControl
xmlns:local="using:ProjectName.Folder">
MainPage.xaml
<Page
xmlns:CustomPrefix="using:ProjectName.Folder">
<CustomPrefix:UserControl />
</Page>
The project needs to be built to discard XAML errors in Visual Studio, otherwise the design view remains blank and the XAML has green squiggles.

wp7 Date Formatting during Binding

I tried following the following example with no luck:
http://msdn.microsoft.com/en-us/library/system.windows.data.ivalueconverter%28v=VS.95%29.aspx
I also tried to follow this as well:
Formatting a date in XAML on WP7
I can't get it to work. When I try to add a reference such as:
<namespace:dateTimeConverter x:Key="MyDateTimeToStringConverter"/>
or
<src:DateConverter x:Key="dateConverter"/>
I'm not sure what I'm doing wrong. Any assistance is appreciated!
Here is my class code:
using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Windows.Data;
using System.Globalization;
namespace OilChangeApplication
{
public class dateTimeConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
DateTime date = (DateTime)value;
return date.ToShortDateString();
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
string strValue = value as string;
DateTime resultDateTime;
if (DateTime.TryParse(strValue, out resultDateTime))
{
return resultDateTime;
}
return DependencyProperty.UnsetValue;
}
}
}
Here is my windows phone form xaml:
<phone:PhoneApplicationPage
x:Class="OilChangeApplication.historyInfo"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:phone="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone"
xmlns:shell="clr-namespace:Microsoft.Phone.Shell;assembly=Microsoft.Phone"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
FontFamily="{StaticResource PhoneFontFamilyNormal}"
FontSize="{StaticResource PhoneFontSizeNormal}"
Foreground="{StaticResource PhoneForegroundBrush}"
SupportedOrientations="Portrait" Orientation="Portrait"
mc:Ignorable="d" d:DesignHeight="696" d:DesignWidth="480"
shell:SystemTray.IsVisible="True">
<!--LayoutRoot is the root grid where all page content is placed-->
<Grid x:Name="LayoutRoot" Background="Transparent">
<Grid.Resources>
</Grid.Resources>
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<!--TitlePanel contains the name of the application and page title-->
<StackPanel x:Name="TitlePanel" Grid.Row="0" Margin="12,17,0,28">
<TextBlock x:Name="ApplicationTitle" Text="Change your Oil Application 2.0" Style="{StaticResource PhoneTextNormalStyle}"/>
<TextBlock x:Name="PageTitle" Text="history" Margin="9,-7,0,0" Style="{StaticResource PhoneTextTitle1Style}"/>
</StackPanel>
<ListBox Grid.Row="1">
<Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
<ListBox Height="601" HorizontalAlignment="Left" Margin="-3,2,0,0" Name="lbHistory" VerticalAlignment="Top" Width="460" ItemsSource="{Binding historyItemsCollection}">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel x:Name="DataTemplateStackPanel" Orientation="Horizontal">
<TextBlock FontFamily="Segoe WP Semibold" FontWeight="Bold" FontSize="30" VerticalAlignment="Top" Margin="20,10">*</TextBlock>
<StackPanel>
<TextBlock x:Name="ItemText" Text="{Binding VehicleName}" FontSize="{StaticResource PhoneFontSizeLarge}"/>
<StackPanel Orientation="Horizontal"
HorizontalAlignment="Center"
VerticalAlignment="Center">
<!--<TextBlock x:Name="ocDate" Text="{Binding OilChangedDate}"></TextBlock>-->
<TextBlock Text="{Binding OilChangedDate, Converter={StaticResource dateTimeConverter},ConverterParameter=\{0:M\}}" />
<TextBlock x:Name="ocOdometer" Text="{Binding OilChangedOdometer}" FontSize="{StaticResource PhoneFontSizeNormal}"/>
</StackPanel>
</StackPanel>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</Grid>
</ListBox>
</Grid>
<!--Sample code showing usage of ApplicationBar-->
<phone:PhoneApplicationPage.ApplicationBar>
<shell:ApplicationBar IsVisible="True" IsMenuEnabled="True">
<shell:ApplicationBarIconButton IconUri="/Images/check.png" Text="save" x:Name="btnSave" Click="btnSave_Click"/>
<shell:ApplicationBarIconButton IconUri="/Images/cancel.png" Text="cancel" x:Name="btnCancel" Click="btnCancel_Click"/>
</shell:ApplicationBar>
</phone:PhoneApplicationPage.ApplicationBar>
</phone:PhoneApplicationPage>
I also had a bit of trouble with converters and found an easy work around is to have another property on the class you are binding called something along the lines of DisplayDate.
For example if you are binding OilChangedDate you could add this property to the class you bind:
public string OilChangedDisplayDate
{
get { return OilChangedDate.ToShortDateString(); }
}
Then bind this property instead of the date directly.

Categories

Resources