Playing video in Silverlight with Source binding - silverlight

I am trying to make a WMV video to play in Silverlight MediaElement. It works in this XAML code:
<MediaElement
x:Name="VideoElement"
Stretch="Fill"
Source=""http://ecn.channel9.msdn.com/o9/pdc09/wmv/CL20.wmv""
Grid.Row="0"
Grid.Column="0"
AutoPlay="True"/>
But when I try to bind the source to some property in my code like this:
<MediaElement
x:Name="VideoElement"
Stretch="Fill"
Source="{Binding VidPath}"
Grid.Row="0"
Grid.Column="0"
AutoPlay="True"/>
Where VidPath is:
public Uri VidPath
{
get
{
return new Uri("http://ecn.channel9.msdn.com/o9/pdc09/wmv/CL20.wmv", UriKind.Absolute);
}
set;
}
It doesn't work. Can you help me figure out why?

First, I'll assume this is an out of browser application with full trust, otherwise cross-domain policy restrictions would prevent the MediaElement from playing that video either way.
Given that, there's nothing wrong with the code you've supplied, but I have a hunch the DataContext of the page that contains your MediaPlayer isn't set correctly. If you put a breakpoint in the getter for VidPath, does it ever get hit? I'm betting no.
Whatever object contains your "VidPath" property, you want to make sure that's the DataContext of your page. E.g. if you just put VidPath as a property in the code-behind, you can add this to the constructor:
this.DataContext = this;

Related

MahApps panoram control not displaying photo's

I want use the MahApps PanoramaControl to display a bunch of photo's. However I see only the string paths appear in the control, which will be correct if you look at my code.
But I can't figure out howto get it working to show the images instead of the links.
Xaml:
<Controls:Panorama Grid.Row="2"
Grid.ColumnSpan="4"
ItemBox="140"
ItemsSource="{Binding PhotoCollection, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" />
ViewModel:
string[] filePaths = Directory.GetFiles(#"D:\Google Drive\Images\Backgrounds");
test = new PanoramaGroup("My Photo's", filePaths);
PhotoCollection = new ObservableCollection<PanoramaGroup> { test };
Anyone an idea on how to make it show the images? The control is load as I can scroll sideways on the text.
There is not much documentation on their site on how to get it working...
Or are you using some other Metro style lib for the 4.0 framework?
In order to get MahApps Panorama control i would offer the follow solution below. As to other frameworks that provide this level of detailed MODERN UI experience I have not come across any but interested to know if you do.
Hope the solutions works for you.
You need to add a Data Template the represent the object you're showing.
Start off by defining the object in a POCO class (as illustrated below). Then in the population of the items ensure you translate them to the newly created POCO object instead of leaving them as string values.
public class Photo {
public string Path { get; set; }
}
Next in the definition of you XAML window you need to create a reference to the namespace where the POCO object resides.
xmlns:model="clr-namespace:project.models;assembly=project"
Last, but not least, you want to then create a DataTemplate to represent the object. This is added to the window resources.
<Window.Resources>
<DataTemplate DataType="{x:Type model:Photo}">
<Image Source="{Binding Path}"/>
</DataTemplate>
</Window.Resources>
This should then let the render take place in the interface where it belongs. Hope this works for you.

Silverlight - bind to URL

For some reason when I put
"Img/Covers/Medium/106.jpg"
EDIT:
<Image Grid.Column="0" Stretch="None" HorizontalAlignment="Left" Source="Img/Covers/Medium/106.jpg" Margin="7,0,0,0"></Image>
As the Source for an Image, it works perfectly. But when I try to bind the Source to a property defined as such, it doesn't find it.
public virtual Uri MediumImgURI {
get { return new Uri("Img/Covers/Medium/106.jpg"); }
}
EDIT:
<Image Grid.Column="0" Stretch="None" HorizontalAlignment="Left" Source="{Binding Path=MediumImgURI}" Margin="7,0,0,0"></Image>
Is there something special I have to do to get the latter case to work?
EDIT: Also, making that property a string, instead of Uri causes it to work, but this is an over-simplification - I really need to get it to work with the property as Uri.
EDIT:
When I was linking to images that were in my website, and not my SL app, I had this code (which worked)
public virtual string MediumImgURI {
get { return new Uri(App.Current.Host.Source, String.Format("../Img/Medium/{0}.jpg", CurrentBook.smallID)); }
}
When linking instead to an image in my SL app I thought I could just leave off the first parameter, but it appears not.
Yes, hard to tell from what you have posted. It may be that your binding is failing. Try pulling it up in SilverlightSpy3 and see what the Source is for that image.
Sorry everyone - I did a poor job of researching this myself before asking. As noted here,
https://stackoverflow.com/questions/20586/wpf-image-urisource-and-data-binding
it needs to be a Uri relative to the xap file, so I need a ../ in front of my address.
Thanks for answering.

binding an image source in XAML

I am trying to bind an image source to my XAML through c#
this works
<Image Source="images/man.jpg"></Image>
this does not work
<Image Source="images/{Binding imagesource}"></Image>
where imagesource is a string variable in the c# file of this xaml and is being set equal to "man.jpg"
here is a way how to do it in XAML:
add this to the namespace:
xmlns:System="clr-namespace:System;assembly=mscorlib"
then add your images paths
<System:String x:Key="ImageRefresh">/Theme;component/Images/icon_refresh.png</System:String>
<System:String x:Key="ImageSearch">/Theme;component/Images/icon_search.png</System:String>
This is how you use it
<Image Height="16" Source="{StaticResource ImageSearch}" Stretch="Uniform" Width="16"/>
This works ok, but if you load your xaml style in Blend it will go bogus..
An object of type "System.String" cannot be applied to a property that expects the type "System.Windows.Media.ImageSource".
I haven't figured out yet, how to replace System:String with that Media.ImageSource... but hey.. it works for me in Visual Studio.
You can't stick a binding mid-way through the value like that. It's either a binding, or it's not. Assuming imagesource is publicly accessible via your DataContext, you could do this:
<Image Source="{Binding imagesource}"/>
However, if it's been set to "man.jpg" then it won't find the image. Either set imagesource to the full path ("images/man.jpg") or use a converter:
<Image Source="{Binding imagesource, Converter={StaticResource RelativePathConverter}}"/>
The converter would prepend "images/" onto its value. However, it may be necessary for the converter to return an ImageSource rather than a string.
Images have bitten me in the past. There is a certain lookup order involved.
When you use "image/man.jpg" it could refer to a file inside your silverlight xap, or relative to the location of XAP file. For example, it could be in YourProject.Web/ClientBin/image/man.jpg.
You should troubleshoot by using full URLs first and find out if this works.
imagesource needs to be an actual Image object, not a string.
Here is a method that will create a new Image object given a path:
public BitmapImage Load(string path)
{
var uri = new Uri(path);
return new BitmapImage(uri);
}

WPF relative path problem

I have created a custom TaskButton control that takes an image and text. The properties are set like this:
<custom:TaskButton Text="Calendar" ImagePath="Images/calendar.png" ... />
My custom control class implements Text and ImagePath properties, and the control template for the custom control (in Themes\Generic.xaml) sets its content like this, using a RelativeSource object to get the image path:
<!-- Button Content -->
<StackPanel>
<Image Source="{Binding Path=ImagePath, RelativeSource={RelativeSource TemplatedParent}}" Width="24" Height="24" Stretch="Fill" Margin="10,0,0,0" />
<TextBlock Text="{TemplateBinding Text}" HorizontalAlignment="Center" VerticalAlignment="Center" FontFamily="Segoe UI" FontWeight="Bold" Margin="6,0,10,0" Foreground="Black" />
</StackPanel>
The control works fine in most cases, but in a particular project, the relative path to the button's image does not get resolved correctly, and the button image is not displayed. Here is what I have figured out so far:
I am entering the path correctly when I use the custom control. If I place an image control on the same design surface with the same relative path, it is resolved correctly.
The problem is with the relative path. If I replace the relative path with an absolute path, the path is resolved correctly and the image is displayed.
As I mentioned above, the control works fine in most cases. The one case where it isn't working is a Prism 2.1 project, where the control is instantiated on a user control in a Prism module. The module is a simple class library, but it has all of the references of a WPF project.
Any idea why the relative path would fail? Thanks in advance for your help.
I finally figured out the problem. It was actually in the C# backing class for my control. I declared an ImagePath property as a string, since that was how I was going to specify the image. Oops--bad call on my part. That property should actually be an ImageSource property, not a string. WPF has a built-in ImageSourceConverter class that will resolve the path and return the specified image. So, I simply changed the property name from ImagePath to Image, and changed its type from string to ImageSource. That solved the problem.
Thanks to Aviad P. for taking a crack at this. It was unsolvable without the C# code showing the property declarations. I'll post all code and markup next time.

Combobox doesn't bind correctly to SelectedItem

I have two projects. One is working and the other isn't however the differences between them is nothing that I think "should" be of any importance. The first project is the one that is broken and it is the one I am trying to fix. The second project is a little sample project that I created when the first project just won't work at all. Of course the sample works perfectly.
Here is the view for the first project. I have removed a bunch of the "MainWindowTabControlStyle" because it is just the combo box that is broken. I am reasonable certain that the issue is not in the style because it is a copy and paste from the project that is working.
<Grid>
<TabControl Style="{DynamicResource MainWindowTabControlStyle}">
<TabItem Header="Tab 1"/>
<TabItem Header="Tab 2"/>
</TabControl>
</Grid>
<Style x:Key="MainWindowTabControlStyle" TargetType="{x:Type TabControl}">
...
<ComboBox
HorizontalAlignment="Right"
VerticalAlignment="Top"
IsSynchronizedWithCurrentItem="True"
ItemsSource="{Binding Path=Subscriptions, Mode=Default}"
SelectedItem="{Binding Path=SelectedSubscription, Mode=OneWayToSource}"
ItemTemplate="{DynamicResource SubscriptionsItemTemplate}"/>
...
</Style>
<DataTemplate x:Key="SubscriptionsItemTemplate">
<StackPanel Orientation="Horizontal">
<TextBlock Text="{Binding Path=DisplayName, Mode=Default}"/>
</StackPanel>
</DataTemplate>
Here is the view model that is set to the DataContext of the MainWindow. The ViewModelBase class is the exact same code that Josh Smith wrote in this months MSDN article.
public sealed class MainWindowViewModel : ViewModelBase
{
public MainWindowViewModel()
{
}
private ObservableCollection<Subscription> subscriptions;
public ObservableCollection<Subscription> Subscriptions
{
get
{
if (subscriptions == null)
{
subscriptions = new ObservableCollection<Subscription>();
subscriptions.Add(new Subscription() { DisplayName = "ABC" });
subscriptions.Add(new Subscription() { DisplayName = "XYZ" });
subscriptions.Add(new Subscription() { DisplayName = "PDQ" });
}
return subscriptions;
}
set { subscriptions = value; }
}
private Subscription selectedSubscription;
public Subscription SelectedSubscription
{
get { return selectedSubscription; }
set { selectedSubscription = value; }
}
}
When I run the project from the debugger the first think that is called is the getter for the Subscriptions collection. Then the setter is called on the SelectedSubscription (it is null). After that I can change the selected item in the combobox till I am blue in the face and the setter for the SelectedSubscription property doesn't get changed again. It is important to note that the combobox does contain the correct values.
In the second project the code is identical but the first thing that is called is the setter for the SelectedSubscription property (it is null) then the getter for the Subscriptions collection is called and finally the setter for the SelectedSubscription is called a second time and it has a value that matches the first item in the Subscriptions collection.
This little jewel has cost me about 5 hours if you have any ideas at all I am willing to try it.
Thanks
Possibly change
SelectedItem="{Binding Path=SelectedSubscription, Mode=OneWayToSource}"
to
SelectedItem="{Binding Path=SelectedSubscription, Mode=TwoWay}"
Sorry about the delay in getting an answer posted. There was some kind of issue with getting an Open ID up and running.
This is a seriously weird issue.
The resolution to this problem didn't come from the window at all. Prior to the window's show method being called there was another window that was opened as a dialog. In this dialog there was the following resource
<Window.Resources>
<DropShadowBitmapEffect x:Key="DropShadowEffect" Noise="0" Opacity="0.45" ShadowDepth="5" Softness="0.25"/>
</Window.Resources>
It was was being referenced by two textblocks in the same window as a "DynamicResource". After turning off the dialog and making the application start with the windows that was having the problem it was discovered that the issue was being caused by the dialog window. While I was researching the issue a coworker suggest that I turn the DynamicResource into a StaticResource because there was no reason for it to be dynamic.
This change in a dialog window using an resource that was only available within the scope of the dialog window fixed the binding issue described above in the "Main Window". I guess stranger things can happen.
The correct way to debug this is to take the working project and to alternately (modify it to match broken code/confirm it works) until it is either identical to the broken project or it breaks. The point at which it breaks tells you where the problem is. Modifying the broken project is typically a lost cause.
As a secondary point, I'd recommend adding the System.Diagnostics namespace to your XAML. It will make errors show up in the Visual Studio Output window.
xmlns:debug="clr-namespace:System.Diagnostics;assembly=WindowsBase"
As a possibly related point (in that it's not really clear what the problem in the broken project is), you might have a look at this StackOverflow question ("Combobox controling Tabcontrol") that relates to:
WPF,
ComboBoxes,
TabControls, and
binding between them using SelectedIndex.
There isn't yet a solution to this question, but it is a simpler problem.
Lastly, Josh Smith's MSDN code is pretty large. It's hard to figure out what you changed to add your ComboBox without seeing all the code.

Resources