WPF: Changing MediaElement source with ResourceDictionary - wpf

I want to use background music in my WPF Application.
Like you can see here: How to do background music for my WPF-Application?
So I use a MediaElement.
Now I want to change the source of it while running the Application.
I'm already doing something similar with some background pictures. There I have different ResourceDictionaries that I'm switching to show different "themes".
One of my dictionaries looks like this:
<ResourceDictionary
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<ImageBrush x:Key="Backgroundpic" ImageSource="picture.png"/>
...
</ResourceDictionary>
So I can use it in the xaml like this:
...
<Grid x:Name="Bg" Background="{DynamicResource Backgroundpic}"/>
...
But HOW can I do that with my MediaElement-Source that I can use it like this:
<MediaElement x:Name="myMediaElement" Source="{DynamicResource ???}" />
I just don't know what to write into my ResourceDictionary.

Source is a Uri, so you need your resource to be a Uri. (Note that System.Uri is in the System assembly, not mscorlib, so it needs a different XML namespace than you would use for types like String):
<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=System">
<sys:Uri x:Key="mediaSource">something.mp3</sys:Uri>
Then you can reference it with Source={DynamicResource mediaSource}.

Related

Use Resource Dictionary Styles in my class library project without merging dictionaries

I am creating a class library project that will contain WPF user controls. My Requirement is that all controls have the same style. My project looks like:
Things I have done in order to solve this problem:
Added all references needed by a WPF application System.Xaml, WindowsBase, etc.. so that I can have wpf controls in my class library project.
In AssemblyInfo.cs I have added:
[assembly: ThemeInfo(ResourceDictionaryLocation.None, ResourceDictionaryLocation.SourceAssembly)]
Added ResourceDictionary1.xaml To the project adding the style.
<ResourceDictionary
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<SolidColorBrush x:Key="Brush1" Color="#FF19199E"/>
</ResourceDictionary>
Now if I want to use a style on my UserControl1.xaml I do:
<UserControl.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="ResourceDictionary1.xaml" />
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
</UserControl.Resources>
<Grid >
<Rectangle Fill="{StaticResource Brush1}" />
</Grid>
I know it works great but here is the catch. Every time I create a new userControl I will have to merge the dictionary. On a regular WPF application I could just merge the dictionary once on App.xaml and I will be able to use that dictionary on my entire application. How can I avoid having to merge the dictionary every time I create a new userControl? If I plan on addying a new resource dictionary I will have to go to all userControls and merge another dictionary. Perhaps I wrote the question title incorrectly and my question should have been how can I add a App.xaml file to a class library project
You should replace the source value ResourceDictionary1.xaml like the follow:
Source="pack://application:,,,/ControlsDLL;component/ResourceDictionary1.xaml">
or just simple as following:
<UserControl.Resources>
<ResourceDictionary Source="pack://application:,,,/ControlsDLL;component/ResourceDictionary1.xaml"></ResourceDictionary>
</UserControl.Resources>

WPF binding to external style

I have found a framework called VIBlend http://viblend.com/products/net/wpf/controls/free-wpf-controls.aspx. I have downloaded it and there is a dll file containing styles. It contains a dll which contains styles. One of these Styles is contained in a file called ListBox.xaml (compiled in the dll).
It contains a few styles. One of them is declared like this:
Now i am wondering how I can use this style. If created a reference to that dll but now?
I tried this one but it does not work...
<UserControl.Resources>
<ResourceDictionary x:Key="listBoxStyle" Source="Office2010SilverListBoxStyle"/>
</UserControl.Resources>
<ListBox x:Name="listBox" Style="{StaticResource listBoxStyle}">
Try this:
<Application.Resources>
<ResourceDictionary
Source="/PutDllNameHere;component/ListBox.xaml" />
</Application.Resources>

WPF Dynamic Resource Lookup Behavior with FixedPage

Having the following very simple xaml:
<DocumentViewer Name="dv">
<FixedDocument Name="fd" Loaded="fd_loaded">
<FixedDocument.Resources>
<Style x:Key="TestStyle">
<Style.Setters>
<Setter Property="TextBlock.Foreground" Value="BlueViolet"/>
</Style.Setters>
</Style>
<SolidColorBrush x:Key="foregroundBrush" Color="Orange"/>
</FixedDocument.Resources>
<PageContent Name="pc">
<FixedPage Name="fp" Width="800" Height="600" Name="fp">
<TextBlock Name="tb" Style="{DynamicResource TestStyle}">
Lorem ipsum
</TextBlock>
<TextBlock Foreground="{DynamicResource foregroundBrush}" Margin="20">
Lorem ipsum
</TextBlock>
</FixedPage>
</PageContent>
</FixedDocument>
</DocumentViewer>
The use of Dynamic Resources (which I actually need in a more complex situation) here doesn't work. Using Static Resources colors the TextBlocks in the desired colors. Moving the Resources to the level of the FixedPage also does the trick. But I would like to have one generic resource dictionary on a top level element (because of runtime changes the user can make for colours, fonts, etc.). Placing the resources on Application level also does work. But it's not an option for good reasons.
Anybody have any clue why this doesn't work. Does it have something to do with the Logical Tree from the TextBlock upwards?
MSDN Resources Overview states that:
The lookup process checks for the requested key within the resource dictionary defined by the element that sets the property.
If the element defines a Style property, the Resources dictionary within the Style is checked.
If the element defines a Template property, the Resources dictionary within the FrameworkTemplate is checked.
The lookup process then traverses the logical tree upward, to the parent element and its resource dictionary. This continues until the root element is reached.
I also tried putting the Brush and the Style into the Resources of a (dummy) Style according to the above explanation of MSDN. But that didn't work either.
Really have the feeling that this can not be that complex, but most probably I oversee something. Any help is appreciated.
EDIT
When naming the TextBlock to "tb" and then using tb.FindResource("TestStyle") throws an exception. So that resource clearly can't be found. If I check out LogicalTreeHelper.GetParent(tb) and repeat that for the parents found I get the expected result: TextBlock > FixedPage > PageContent > FixedDocument ...
EDIT2
This works perfect. What's the difference with the XAML projected earlier?
<Window x:Class="WpfDynamicStyles2.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<Grid>
<Grid.Resources>
<SolidColorBrush x:Key="resBrush" Color="Orange"></SolidColorBrush>
</Grid.Resources>
<StackPanel>
<Button>
<TextBlock Foreground="{DynamicResource resBrush}">Dummy text...</TextBlock>
</Button>
</StackPanel>
</Grid>
</Window>
EDIT3
private void fd_Loaded(object sender, RoutedEventArgs e)
{
Object obj = pc.TryFindResource("foregroundBrush");
obj = fp.TryFindResource("foregroundBrush");
obj = tb.TryFindResource("foregroundBrush");
}
The dynamic resource placed on the Foreground property of the textbox cannot be resolved (the actual resource is at the FixedDocument.Resources level). Also using the TryFindResource in code behind works from pc (PageContent) but from fp (FixedPage) and tb (TextBlock) it cannot resolve the resource (obj is null). When using a Static Resource in the XAML Markup everything works fine.
Well going the style way is a good design but not necessary. To make dynamic color based same named (keyed) brushes, we can use as dynamic color dictionaries (NOT brush dictionaries)
The solution can be as below ...
Create a single brush resource dictionary.
Refer the color in the brush with DynamicResource attribute.
Create multiple resource dictionaries with same keyed Color resource in each of them them.
Based on user's requirement, clear and add into Application.Current.resources.MergedDictionaries.
Example
Make a WPF project with a window that has following XAML....
<Window.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="Resources/Window11Resources.xaml"/>
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
</Window.Resources>
<DockPanel LastChildFill="True">
<ComboBox DockPanel.Dock="Top" VerticalAlignment="Top"
SelectionChanged="ComboBox_SelectionChanged"
SelectedIndex="0">
<ComboBox.ItemsSource>
<Collections:ArrayList>
<System:String>Orange</System:String>
<System:String>Red</System:String>
<System:String>Blue</System:String>
</Collections:ArrayList>
</ComboBox.ItemsSource>
</ComboBox>
<DocumentViewer>
<FixedDocument>
<PageContent>
<FixedPage Width="793.76" Height="1122.56">
<TextBlock
FontSize="30"
Foreground="{StaticResource LabelColorBrush}"
Text="Test"/>
</FixedPage>
</PageContent>
</FixedDocument>
</DocumentViewer>
If you observe the window doesnt need to use anything which is dynamic. All refernces can remain static. So LabelColorBrush can be found in dictionary Window11Resources.xaml
In Window11Resources.xaml dictionary add a dynamic color brush.
<SolidColorBrush x:Key="LabelColorBrush"
Color="{DynamicResource DynamicColor}"/>
Add following 3 color brush dictionaries in some folder from your project...
<!-- Name = OrangeColorResource.xaml -->
<ResourceDictionary
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<Color x:Key="DynamicColor">Orange</Color>
</ResourceDictionary>
<!-- Name = BlueColorResource.xaml -->
<ResourceDictionary
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<Color x:Key="DynamicColor">Blue</Color>
</ResourceDictionary>
<!-- Name = RedColorResource.xaml -->
<ResourceDictionary
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<Color x:Key="DynamicColor">Red</Color>
</ResourceDictionary>
Note that the key remains the same i.e. DynamicColor.
Now clear and recreate color dictionaries in App.Resources. I have done that in the code behind of Window.xaml.cs
private void ComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
Application.Current.Resources.MergedDictionaries.Clear();
Application.Current.Resources.MergedDictionaries.Add(
new ResourceDictionary()
{
Source = new Uri("Resources\\"
+ ((ComboBox)sender).SelectedItem.ToString()
+ "ColorResource.xaml",
UriKind.RelativeOrAbsolute) });
}
Now as and when you select a color from the drop down, the dynamic color changes on the static resource brush. Note that there is no Style involved.
I hope this answers what you are asking.
By the way: the reason for this post had some more complex background. I really wanted to use a single resource dictionary whereby I could change colors, fonts, fontsizes, etc. dynamically during runtime (by an end-user). I am working on a tax form application. And the tax forms presented on screen for user input are resolving their resources at the Application level. So far so good.
But at the same time I want to present the user a print preview of the tax form where the same resourcedictionary (as object type, not as object instance) is used to define color schemes, fonts, fontsizes, etc. to be used for printing. Which can differ from the styling used for on screen user input. That's why I wanted to "attach" the resource dictionary on (for example) the FixedDocument level so that all pages in the document would refer to it. And when changing colors, fonts etc. all pages with common elements (TextBlocks, TextEditors, etc.) would respond to the change.
And then I became stuck...as described in this post.
For now I have a nice workaround by creating a specific instance of the resourcedictionary, storing it as a private variable and attach it to every individual page I put in the fixed document. It works and that already pleases me. But my programmers heart is still a little ached, because I would prefer to use a single instance of the resource dictionary and put it at some top level control so all controls in it can use it.
As a programmer we have to live with workarounds as well ;) If you have any further suggestions, I'm open to receive them. Thanx for your support thus far.
Greetz, Joep.
Also see: MSDN Forum Post about this issue

How to specify path for file from different project in WPF?

I've got two projects in WPF and one project is the main one and the second one is just for testing (it uses files of the main project - files are added via Project -> add -> Existing items... -> selected file -> add as link so that the file is only in the main project really).
Folders with projects are these:
C:\Work\...\Projects\Main
C:\Work\...\Projects\XXXTestProject
where XXX stands for different parts of the Main project which I test separately.
I've got the code:
<Window x:Class="Sokoban.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:Sokoban"
xmlns:diag="clr-namespace:System.Diagnostics;assembly=WindowsBase"
Title="Window1" Height="559" Width="419">
<Window.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="GameDesk.xaml" />
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
</Window.Resources>
<Grid>
<Rectangle local:GameDeskProperties.FieldSize="30" Name="myrect" Style="{DynamicResource GameDesk}" MouseEnter="Rectangle_MouseEnter" />
</Grid>
</Window>
... which should use XAML resources from GameDesk.xaml which is in the main project and it seems that I can't use Pack URI (http://msdn.microsoft.com/en-us/library/aa970069.aspx). How can I specify the file?
Should I use absolute path? (C:\Work...\Main\Resources\GameDesk.xaml)
Or is there any other way?
Thank you for help!
MSDN link here
Use a pack:// URI of the form:
pack://application:,,,/ReferencedAssembly;component/Subfolder/ResourceFile.xaml
if the XAML is in a referenced assembly
or
pack://siteoforigin:,,,/Subfolder/SiteOfOriginFile.xaml
if the XAML is loose and copied to the bin folder.

Image shows in Expression Blend but not during runtime

The image in question is located in a ControlTemplate inside of a ResourceDictionary similar to this (various details removed for clarity):
<ResourceDictionary
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">
<ControlTemplate x:Key="ImageTestTemplate" TargetType="ImageTest">
<Grid>
<Image Source="/MyAssembly;Component/Images/MyImage.png"/>
</Grid>
</ControlTemplate>
</ResourceDictionary>
When I view the control in Expression Blend the image shows up just fine, but when I run the app the image does not show up. If I drop the same image into a UserControl it also shows up just fine, so the problem has something to do with using the template.
Is there some other way I should be loading the image resource inside the template?
I don't think you need the leading '/'. The base resource path I'm using for a project is "IMLPrototype2;component/Model/Sounds/" in SL 3 & 4.

Resources