How to bind string of class to resource dictionary - wpf

I have many tooltips saved in file hints.xaml . Like this :
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:WpfApp7.Theme"
x:Class="WpfApp7.Theme.Hints">
<ToolTip x:Key="myToolTip" >
<StackPanel >
<Label Content="Nadpis" />
<TextBlock Text="................"/>
</StackPanel>
</ToolTip>
</ResourceDictionary>
How i can bind string of class Enviroment.CurrentDictionary on my Text="................" ?
I tried to create code behind for Hints.xaml and bind by DataContext but didnt work .

Try this:
<StackPanel xmlns:system="clr-namespace:System;assembly=mscorlib">
<Label Content="Nadpis" />
<TextBlock Text="{x:Static system:Environment.CurrentDirectory}"/>
</StackPanel>

Related

WPF - DataBinding (Command is not being executed)

I am writing a WPF application where I wish to implement the MVM pattern.
My code is currently set up like this:
This is my view model class where I am exposing the command I wish to be executed as a property
```
public HomeScreenViewModel(NavigationService mw)
{
this.mw = mw;
}
private RelayCommand _addStudent;
public ICommand AddStudent
{
get
{
if (_addStudent == null)
{
_addStudent = new RelayCommand(param => this.OpenNewStudents(), param => true);
}
return _addStudent;
}
}
This is my xaml containing the layout of the corresponding view
<Page x:Class="test.HomeScreen"
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:local="clr-namespace:test"
mc:Ignorable="d"
d:DesignHeight="450" d:DesignWidth="1300"
Title="HomeScreen">
<WrapPanel VerticalAlignment="Center" HorizontalAlignment="Center">
<WrapPanel HorizontalAlignment="Center" Height="300" Margin="0,0,0,0" VerticalAlignment="Center" Width="1300">
<Button Content="AddStudent" Command="{Binding AddCommand}" Style="{StaticResource ButtonStyle}" />
<Button Content="AddStudent" Style="{StaticResource ButtonStyle}" />
<Button Content="AddStudent" Style="{StaticResource ButtonStyle}" />
<Button Content="AddStudent" Style="{StaticResource ButtonStyle}" />
<Button Content="AddStudent" Style="{StaticResource ButtonStyle}" />
<Button Content="AddStudent" Style="{StaticResource ButtonStyle}" />
<Button Content="AddStudent" Style="{StaticResource ButtonStyle}" />
<Button Content="AddStudent" Style="{StaticResource ButtonStyle}" />
<TextBox Text="{Binding Path=HI}" Width="200" Height="200"/>
</WrapPanel>
<Canvas Margin="350, 100,0, 0" Height="300" Width="1350" VerticalAlignment="Center" HorizontalAlignment="Center">
<Image Source="Logo.PNG"/>
</Canvas>
</WrapPanel>
I have set the command of the top button using the binding syntax in the WrapPanel.
This HomeScreen page is linked from a naviagation window and is the source of the navigation window (xaml file):
<NavigationWindow x:Class="test.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:test"
mc:Ignorable="d"
Title="School Management App" Height="350" Width="1250"
Source="HomeScreen.xaml">
</NavigationWindow>
I have my HomeScreen view constructor set like this:
public partial class HomeScreen : Page
{
public HomeScreen()
{
InitializeComponent();
this.DataContext = new HomeScreenViewModel(this.NavigationService);
}
}
My infrastructure is set up as I have described above and my implementation of relay command is taken from this site https://msdn.microsoft.com/en-us/magazine/dd419663.aspx.
When I run my application and I press the corresponding button, nothing happens. I was wondering if someone could help me figure out what is wrong and why the command binding isn't working. It would be much appreciated, thanks :)
as a side note, could someone give me some tips on what the best way to debug wpf applications and figure out what bindings exist at run time.
Thanks :)
your command name is AddStudent, but you use AddCommand in xaml. Just correct the name:
Command="{Binding AddStudent}"

Define Source one time and use it many times

Currently I am using the below code to Bind to the TextBlock to the Application Settings
<Grid DataSource="{Binding DataContext.CurrentPatient, RelativeSource={RelativeSource AncestorType={x:Type Page}}">
...
...
...
<TextBlock Text="{Binding Source={StaticResource Settings}, Path=Default.Test}" />
<TextBox Text="{Binding Source={StaticResource Settings}, Path=Default.CurrentValue}" />
<TextBlock Text="{Binding Source={StaticResource Settings}, Path=Default.NormalValue}" />
...
...
...
</Grid>
Now I don't want to type Source={StaticResource Settings} in all the textblocks.
In short I want Code-minification. I mean I want my code to be maintainable and reduced.
Try this
public class Mybinding : Binding
{
//Load only once and use every time :)
static object Settings = App.Current.Resources["Settings"];
public Mybinding()
{
Source = Settings;
}
}
<TextBlock Text="{local:Mybinding Path=Default.Test}" />
>Edit
<Application.Resources>
<ResourceDictionary>
<properties:Settings x:Key="Settings" />
</ResourceDictionary>
</Application.Resources>
local is the namespace of Mybinding. I havent tested it .But hope this will give you an idea.And am Expecting "Settings" is in App.xaml or in ResourceDictionary Merged to App.xaml
Add one more grid and use its DataContext:
<Grid DataContext={Binding Source={StaticResource Settings}}>
<TextBlock Text="{Binding Default.Test}" />
<TextBox Text="{Binding Default.CurrentValue}" />
<TextBlock Text="{Binding Default.NormalValue}" />
<Grid>

How to make binding from user control to property of parent control?

I've seen similar questions, but I still not able to do my need. I need to output checkbox's name through a label inside a user control:
Window1.xaml:
<Window x:Class="WpfBinding.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:WpfBinding" Title="Window1" Height="300" Width="300">
<Grid>
<CheckBox Name="checkBox1">
<local:UserControl1></local:UserControl1>
</CheckBox>
</Grid>
</Window>
UserControl1.xaml:
<UserControl x:Class="WpfBinding.UserControl1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<Canvas>
<Label Content="{Binding ElementName=checkBox1, Path=Name}"></Label>
</Canvas>
</UserControl>
How to do it correctly? What lack of knowledge I have? Thanks for help.
Above solution will work, but a more direct solution for this specific problem would be to use RelativeSource binding in your user control as below:
<Canvas>
<Label Content="{Binding RelativeSource={RelativeSource AncestorType=CheckBox, AncestorLevel=1}, Path=Name}"></Label>
</Canvas>
Hope this is what you need !!!
ElementName binding works within in same XAML scope. This will work -
<Grid>
<CheckBox Name="checkBox1"/>
<Label Content="{Binding ElementName=checkBox1, Path=Name}"/>
</Grid>
But if you want to do it in different UserControl, you have to tweak a bit your code and use Tag to hold name -
<Grid>
<CheckBox Name="checkBox1">
<local:UserControl1 Tag="{Binding ElementName=checkBox1, Path=Name}"/>
</CheckBox>
</Grid>
UserControl.xaml
<Canvas>
<Label Content="{Binding Path=Tag, RelativeSource={RelativeSource
Mode=FindAncestor, AncestorType=UserControl}}"/>
</Canvas>
On a sidenote, in your UserControl, you know you need to bind with ElementName = checkBox1 and that's the name only you are binding to. Its something equivalent to -
<Label Content="checkBox1"/>

WPF binding root element of xaml file does not work:

I was trying to bind a dataContext to a grid (xaml below)
<Grid .... DataContext="{Binding Path=NewFormViewModel}" > ...</Grid>
This binding did not work and I realized the getter for NewFormViewModel was never being called.
At this point in time, The grid was the root element of the xaml file.
I then placed a canvas inside the Grid and did binding on the canvas like :
<Grid ....>
<Canvas DataContext="{Binding Path=NewFormViewModel}">
....
</Canvas>
</Grid>
The data binding worked.
Next I tried to change the grid to a canvas and do databinding agiain like this:
<Canvas.... DataContext="{Binding Path=NewFormViewModel}" > ...</Canvas>
The binding stopped working again.
In the end I settled for a Grid nested inside a canvas:
<Canvas....>
<Grid DataContext="{Binding Path=NewFormViewModel}">
....
</Grid>
</Canvas>
The question is why did the binding on the root element of the xaml not work?
or Should I have not used a Canvas/Grid as a root element at all and used something like Page/UserControl?
EDIT
My logical tree looks somthing like this:
Window <- Data binding to object o
|
*
Frame <-Data binding to obect o inherited
|
*
Canvas/Grid <- Data binding to o.NewFormViewModel failed
|
*
Canvas/Grid <- Data binding to o.NewFormViewModel Succeeds
EDIT2:
broken xaml:
<Canvas x:Class="WPFEditors.NewForm"
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" Height="398" Width="377"
DataContext="{Binding Path=NewFormViewModel}"
>
<Grid >
<Label DataContext="Form Type" Height="31" HorizontalAlignment="Left" Margin="12,22,0,0" VerticalAlignment="Top" Width="92" />
<ComboBox Margin="148,22,6,347" ItemsSource="{Binding Path=FormTypes}" />
<Label Content="Description" Height="31" HorizontalAlignment="Left" Margin="12,58,0,0" VerticalAlignment="Top" Width="92" />
<Label Content="{Binding Path=Heading}" ToolTip="This is pulled from the Enum defined for FormTypes" Margin="148,59,6,309" />
<Label Content="Version" Height="31" HorizontalAlignment="Left" Margin="12,95,0,0" VerticalAlignment="Top" Width="92" />
<TextBox Text="Bind this later" Margin="148,97,6,270" Height="31" />
<Label Content="Approval Level" Height="31" HorizontalAlignment="Left" Margin="12,132,0,0" VerticalAlignment="Top" Width="92" />
<TextBox Height="31" Margin="148,134,6,233" Text="Bind this later" />
<Label Content="Number of Approvals" Height="31" HorizontalAlignment="Left" Margin="12,171,0,0" VerticalAlignment="Top" Width="130" />
<TextBox Height="31" Margin="148,173,6,194" Text="Bind this later" />
<Label Content="Heading" Height="31" HorizontalAlignment="Left" Margin="12,210,0,0" VerticalAlignment="Top" Width="130" />
<TextBox Height="31" Margin="148,212,6,155" Text="Bind this later" />
<Label Content="Static Data Id" Height="31" HorizontalAlignment="Left" Margin="12,247,0,0" VerticalAlignment="Top" Width="130" />
<TextBox Height="31" Margin="148,249,6,118" Text="Bind this later" />
<Label Content="{Binding Path=Errors}" Background="{Binding Path=Color}" Margin="12,325,6,6" BorderThickness="1" BorderBrush="#FF000019" />
<Button Content="Create" Margin="83,294,202,78" />
<Button Content="Create" Margin="181,294,104,78" />
<Button Content="Create" Margin="279,294,6,78" />
</Grid>
</Canvas>
In the above xaml the following line binds:
<Label Content="{Binding Path=Heading}"
even though Heading is inside a property of the viewmodel that this document inherits.
At this point I would have expected the line:
DataContext="{Binding Path=NewFormViewModel}"
to have changed the datacontext to NewFormViewModel which has no heading. All the remaining bindings fail.
If I change the beginning to :
<Canvas x:Class="NewForm"
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" Height="398" Width="377"
>
<Grid DataContext="{Binding Path=NewFormViewModel}" >
The binding to Heading fails and the rest of the bindings start to work. This is the behaviour that I was expecting initially.
This xaml is nested in this file :
<Window x:Class="WPFEditors.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="{Binding Path=Heading}" Height="743" Width="1177">
<StackPanel >
<Menu IsMainMenu="True" >
<MenuItem Header="New">
<MenuItem Header="New Form" Command="{Binding Path=MenuCommand}" />
</MenuItem>
<MenuItem Header="Edit Form" ItemsSource="{Binding Path=FormsAvailable}" />
<MenuItem Header="Edit Rules" />
</Menu>
<Frame NavigationUIVisibility="Hidden" Source="{Binding Path=CurrentPage}"
LoadCompleted="Frame_LoadCompleted"
DataContextChanged="Frame_DataContextChanged"
Name="frame">
</Frame>
</StackPanel>
</Window>
and the event handlers to copy the data context to the child are :
private void Frame_LoadCompleted(object sender, NavigationEventArgs e)
{
UpdateFrameDataContext();
}
private void Frame_DataContextChanged(object sender, DependencyPropertyChangedEventArgs e)
{
UpdateFrameDataContext();
}
private void UpdateFrameDataContext()
{
var content = frame.Content as FrameworkElement;
if (content == null)
return;
content.DataContext = frame.DataContext;
}
The Binding in the root element should work IF there is something up in the control hierarchy (like a Window or UserControl) that holds (in its DataContext) the object owning the property you're querying (NewFormViewModel).

WPF UserControl or ControlTemplate... (not sure)

I have a listbox where I have to add about 20 static custom items. All the items are based on the same template (something like that) :
<Border>
<StackPanel Orientation="Horizontal">
<Image Source="" Height="30" />
<TextBlock Text="" VerticalAlignment="Center" />
</StackPanel>
</Border>
I don't want to repeat that 20 times in the ListBox.Items I would like to have some kind of UserControl where I could do something Like the following where I could set some custom properties :
<ListBox>
<ListBox.Items>
<MyListBoxTemplate x:Name="Item1" ItemText="Item #1" ItemImageSource="/Image1.jpg" />
<MyListBoxTemplate x:Name="Item2" ItemText="Item #2" ItemImageSource="/Image2.jpg" />
...
</ListBox.Items>
</ListBox>
But I don't wan't to create a userControl just for that!!! Is there an easy way to put that template in the Window.Resources?
Thanks
If you are ONLY using it for that SPECIFIC listbox, you can just assign the ItemTemplate property. This will need to work in conjunction with a collection of custom objects defined in your resources somewhere else. This will save you from creating a custom UserControl, but you will need an object that can be defined in XAML and a list of them in XAML anyway. To be honest, creating a UserControl is relatively painless and may be easier, but it is possible without doing so.
<ListBox>
<ListBox.ItemTemplate>
<DataTemplate TargetType="CustomObjectType">
<Border>
<StackPanel Orientation="Horizontal">
<Image Source="{Binding ImageSource}" Height="30" />
<TextBlock Text="{Binding TextContent}" VerticalAlignment="Center" />
</StackPanel>
</Border>
<DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
EDIT: If you are going to use it in more than one place, put the DataTemplate in your Application resources and ive it a key, then assign the ItemTemplate property to {StaticResource MyListBoxItemsTemplateKey}
Not my favorite approach since it uses the XmlDataProvider and XPath syntax (which I tend to always forget). But you can embed your static data as xml within your Window.Resources like so:
<Window xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<Window.Resources>
<XmlDataProvider x:Key="MyStaticData" XPath="StaticItems" >
<x:XData>
<StaticItems xmlns="">
<StaticItem>
<ItemText>Item #1</ItemText>
<ItemImageSource>/Image1.jpg</ItemImageSource>
</StaticItem>
<StaticItem>
<ItemText>Item #2</ItemText>
<ItemImageSource>/Image2.jpg</ItemImageSource>
</StaticItem>
</StaticItems>
</x:XData>
</XmlDataProvider>
</Window.Resources>
<Grid>
<ListBox>
<ListBox.ItemsSource>
<Binding Source="{StaticResource MyStaticData}" XPath="StaticItem" />
</ListBox.ItemsSource>
<ListBox.ItemTemplate>
<DataTemplate>
<Border>
<StackPanel Orientation="Horizontal">
<Image Source="{Binding XPath=ItemImageSource}" Height="30" />
<TextBlock Text="{Binding XPath=ItemText}" VerticalAlignment="Center" />
</StackPanel>
</Border>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</Grid>
</Window>
Then within your ListBox bind to the XmlDataProvider you specified and use the XPath notation within the bindings to drill down to the data you want the controls to bind to.
This site has a couple good examples too:
http://vbcity.com/blogs/xtab/archive/2010/12/24/more-xpath-examples-in-a-wpf-application.aspx
Hope this helps!

Resources