Set resource string to XAML - c#

I know how to set string from resource
<TextBlock x:Uid="Text1"/>
where Text1.Text is "Hello"
But I want to do like this
<TextBlock Text = {something here to get GreetingText}/>
where GreetingText is "Hello"
So that I may get the same string from code also as
var loader = new Windows.ApplicationModel.Resources.ResourceLoader();
var string = loader.GetString("GreetingText");

Include this
xmlns:system="clr-namespace:System;assembly=mscorlib"
Have a resource of system:string like this.
<Window.Resources>
<system:String x:Key="GreetingText">Hello</system:String>
</Window.Resources>
and use it in xaml as
<TextBlock Text="{StaticResource GreetingText}" />
and use it in code behind as
string s = (string)objectofMainWindow.Resources["GreetingText"];
Edit: Answer to your comment
Its this way. Resource Dictionary is inside Window.Resources
<Window
xmlns:system="clr-namespace:System;assembly=mscorlib"
Your Rest namespaces
/>
<Window.Resources>
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:ATTFamilyMap.strings">
<system:String x:Key="GreetingText">Hello</system:String>
</ResourceDictionary>
</Window.Resources>
Your Code
</Window>

Nikhil's answer is on the right track, but is right for other platforms.
For windows 8, you need to do the following in your resource directory:
<x:String x:Key="MyString">This is a resource</x:String>
In your xaml:
<TextBlock Text="{StaticResource MyString}"/>
In code:
string myString = (string)(App.Current.Resources["MyString"]);

Related

How to get the actual object of StaticResource from codebehind without using TryFindResource?

I have used a StaticResource in XAML file. I have named the StaticResource using x:Name. Now I want to access the actual object of the StaticResource.
Here are the files:
In XAML file:
<Window x:Class="MyProject.MainWindow"
...
Title="MainWindow" Height="350" Width="525">
<Grid>
<StaticResource ResourceKey="MyButtonResource" x:Name="MyResource" />
</Grid>
</Window>
In Code-behind CS file:
Button buttonFromStaticResource = MyResource.SomeProperty as Button;
Here, I need something like SomeProperty or any method to get the actual object (in this case, it is a Button object).
Edit:
A way to get the object is to use TryFindResource:
Button buttonFromStaticResource = this.TryFindResource("MyButtonResource") as Button;
But this solution involves a string parameter. Any better solution than this so that I can use MyResource directly (by leveraging x:Name in XAML file), without using any string?
How to read static Resource in c#, Check a below code
<Window x:Class="MyProject.MainWindow"
...
Title="MainWindow" Height="350" Width="525">
<Grid>
<StaticResource ResourceKey="MyButtonResource" x:Name="MyResource" />
</Grid>
</Window>
c#
var currentResources= this.Resources["MyButtonResource"];

Dynamic values like digit at ResourceDictionary

For example i have smth like this
<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="USERNAME_AUTH_CONTENT">User auth success</sys:String>
</ResourceDictionary>
and in code behind, sometimes, I use this
var text = findRes("USERNAME_AUTH_CONTENT");
Is it possible to make smth like this:
<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="USERNAME_AUTH_CONTENT">User %username auth success</sys:String>
</ResourceDictionary>
and at codebehind
var text = findRes("USERNAME_AUTH_CONTENT", "here is i want to paste username");
in the end I want see this: 'User AwesomeUserName auth success'
In c++ I can use %d for string. What about c# and resources?
C# uses {0}, {1}, etc, placeholders for string formatting.
declare xaml resource with a placeholder
<system:String x:Key="USERNAME_AUTH_CONTENT">User {0} auth success</system:String>
and use String.Format to apply formatting:
var text = FindResource("USERNAME_AUTH_CONTENT") as string;
if (text != null)
{
text = String.Format(text, "AwesomeUserName");
}
note also that you can use format string directly from xaml:
<TextBlock Text="{Binding Source='AwesomeUserName', StringFormat={StaticResource USERNAME_AUTH_CONTENT}}"/>
(Source='AwesomeUserName' is just an example, if you have a view model, then use Binding Path=SomeProperty)

StaticResource Binding doesn't work as ImageSource

If I use this code:
<btn:Button ButtonImage="{Binding Path=BtnImage, FallbackValue=../Images/Search.png}"/>
my Button has a default image if BtnImage isn't set. When I try to change it into:
<UserControl.Resources>
<ImageSource x:Key="DefaultImage">
../Images/Search.png
</ImageSource>
</UserControl.Resources>
...
<btn:Button ButtonImage="{Binding Path=BtnImage, FallbackValue={StaticResource DefaultImage}}"/>
My default image isn't displayed. I want to understand why and how can I fix this because I am a fan of this StaticResource approach.
Edit:
My used Button is a dummy one:
<UserControl x:Class="WPF_Controls.Controls.Button"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Name="Btn">
<Button DataContext="{Binding ElementName=Btn}"
Command="{Binding Path=ButtonCommand}">
<Image Source="{Binding Path=ButtonImage}" />
</Button>
</UserControl>
Solution:
If I use:
<UserControl.Resources>
<system:String x:Key="DefaultImage">pack://application:,,,/DK_WPF_Controls;component/Images/Search.png</system:String>
</UserControl.Resources>
everything works as expected!
In case there is an "Images" folder in your Visual Studio project, which contains the "Search.png" file, and the file's Build Action is set to Resource, the following should work:
<UserControl.Resources>
<BitmapImage x:Key="DefaultImage" UriSource="/Images/Search.png"/>
</UserControl.Resources>
where
UriSource="/Images/Search.png"
is a XAML shortcut for a full Resource File Pack URI, i.e.
UriSource="pack://application:,,,<assembly name>;component/Images/Search.png"
Alternatively you can also use implicit conversion from string to ImageSource like
<ImageSource x:Key="DefaultImage">/Images/Search.png</ImageSource>

Custom Markup Extension for Data Context Always Treated as type System.Object

I'm trying to create a custom XAML markup extension that will take a type as an argument, and at runtime, resolve that type using an IoC container, but at design time, simply create it using the default constructor. For now, I'm just trying to implement the default constructor portion. It will look like this:
<UserControl ...
DataContext="{custom:MyCustomExtension MyType}"
<TextBox Text="{Binding SomeProperty}" />
</UserControl>
The issue is that the designer always treats the value my extension produces as type object, so I can't use the GUI binding tools, yet it works fine during runtime.
Here's my very basic implementation to reproduce the issue.
[MarkupExtensionReturnType(typeof(object))]
public class MyCustomExtension : MarkupExtension
{
[ConstructorArgument("dataContextType")]
public Type DataContextType { get; set; }
public MyCustomExtension () { }
public MyCustomExtension (Type dataContextType)
{
DataContextType = dataContextType;
}
public override object ProvideValue(IServiceProvider serviceProvider)
{
return Activator.CreateInstance(DataContextType);
}
}
I've tried using reflector to study how StaticResourceExtension does it, because while it also has the [MarkupExtensionReturnType(typeof(object))] attribute, the VS designer has no issue using the real type of the resource being referenced, but couldn't find anything special using that route.
I tried your custom markup extension in Blend (Microsoft Blend for Visual Studio Professional 2015) and it worked for me:
The change in this "Create Data Binding" window is only visible after a rebuild.
My XAML:
<Window x:Class="DesignTimeTypedDataContext.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:DesignTimeTypedDataContext"
mc:Ignorable="d"
Title="MainWindow" Height="350" Width="525"
DataContext="{local:MyCustom {x:Type local:MainWindowViewModel}}">
<Grid>
<TextBlock x:Name="textBlock" HorizontalAlignment="Left" Margin="14.862,19.706,0,0" TextWrapping="Wrap" Text="{Binding Text}" VerticalAlignment="Top"/>
</Grid>
</Window>
BTW, I guess you know this, but there is d:DataContext which gives you a design time DataContext without affecting the runtime.
<Window x:Class="DesignTimeTypedDataContext.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:DesignTimeTypedDataContext"
mc:Ignorable="d"
Title="MainWindow" Height="350" Width="525"
d:DataContext="{d:DesignInstance {x:Type local:MainWindowViewModel}}">
<Grid>
<TextBlock x:Name="textBlock" HorizontalAlignment="Left" Margin="14.862,19.706,0,0" TextWrapping="Wrap" Text="" VerticalAlignment="Top"/>
</Grid>
</Window>
Maybe this is not much of an answer, just thought I'd share it, maybe it helps in debugging. Now at least you that know your code works for some :)

Can't access Windows 8 Store user control from code

I'm writing a Windows 8 Store application and within that I've designed my own user control.
Here is the code for my usercontrol (This is a dummy control but the problem exists with this):
<UserControl
x:Class="Windows8StoreTest.TestUserControl"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:Windows8StoreTest"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
Width="70"
Height="40">
<StackPanel>
<Button Content="Hello" Foreground="Pink" BorderBrush="Pink"/>
</StackPanel>
</UserControl>
I've dropped the user control onto my page and give it a name:
<Page
x:Class="Windows8StoreTest.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:Windows8StoreTest"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d">
<Grid Background="{StaticResource ApplicationPageBackgroundThemeBrush}">
<local:TestUserControl Name="testControl"/>
</Grid>
</Page>
However, when I go to the code behind I can't access the control by that name. It doesn't seem to exist! What is weird is that the control doesn't exists within InitializeComponent() method for the MainPage class which will be why it does exist.
What am I missing from my user control?
I'm using Windows 8 Store, XAML, c#.
Thanks in advance
Try to use this:
<local:TestUserControl x:Name="testControl"/>
Should work...
hello i don't know what is wrong but it should work.i have just made a sample example of it..i am putting it here hope you have done the same way.
<Page
x:Class="App12.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:App12"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d">
<Grid Background="{StaticResource ApplicationPageBackgroundThemeBrush}">
<local:MyUserControl1 x:Name="hellousercontrol" />
</Grid>
in my mainpage.cs.. i have just use it like this..
public MainPage()
{
this.InitializeComponent();
hellousercontrol.Height = 100;
}
one more this..have build your solution ?
I had the same issue in c++ environment. I observed, I didn't had default constructor in my class, as soon as I added the default constructor, I could use the defined UserControl in my project through XAML file. However without default constructor I was able to use it from within c++ code.

Categories

Resources