I have Music folder in my solution explorer..then i want to add that songs to the list box control after that i want to play the selected songs from listbox in the media element using wpf?
Please Help me.
Thanks
To make play behaviour eexplici on a button click , refer this:
Xaml :
<MediaElement x:Name="media" Source="{Binding
ElementName=listbox,Path=SelectedItem}"
LoadedBehavior="Manual" UnloadedBehavior="Manual"/>
<Button Click="Button_Click" Height="27" VerticalAlignment="Bottom"
HorizontalAlignment="Left" Width="62">Play</Button>
Code Behind :-
private void Button_Click (object sender, RoutedEventArgs e) {
media.Play ();
}
You should implement business logic to browse the directory you are targetting. Prepare a collection of Items. Bind these to Listbox
For playing the song, bind selected item to MediaElement.
I will try to compile some simple solution and update if you still need further help.
Updating simple solution:
Xaml:
<StackPanel Orientation="Vertical">
<ListBox ItemsSource="{Binding}" x:Name="fileList"></ListBox>
<MediaElement x:Name="mediaElement" Source="{Binding ElementName=fileList, Path=SelectedItem}"/>
</StackPanel>
Code Behind:
public partial class Window1 : Window {
ObservableCollection<string> mFileList;
public Window1 () {
InitializeComponent ();
GetFiles(#"..\songs");
this.DataContext = mFileList;
}
private void GetFiles (string folderPath) {
string[] files = Directory.GetFiles(folderPath);
mFileList = new ObservableCollection<string> (files);
}
}
You need to handle the mediaended event as below :-
<MediaElement x:Name="media" Source="{Binding ElementName=listbox,Path=SelectedItem}" MediaEnded="media_MediaEnded"
></MediaElement>
Codebehind :-
` private void media_MediaEnded (object sender, RoutedEventArgs e) {
if (listbox.SelectedIndex < listbox.Items.Count - 1) {
listbox.SelectedIndex = listbox.SelectedIndex + 1;
}`
You need to handle the mediaended event as below :-
<MediaElement x:Name="media" Source="{Binding ElementName=listbox,Path=SelectedItem}" Margin="0,119,78,64" MediaEnded="media_MediaEnded"
></MediaElement>
private void media_MediaEnded (object sender, RoutedEventArgs e) {
if (listbox.SelectedIndex < listbox.Items.Count - 1) {
listbox.SelectedIndex = listbox.SelectedIndex + 1;
}
}
Related
Got a WPF application which has an on hover popup. The popup contains a list of different files which can be opened (e.g. pdf, excel etc)
You can navigate and select a file by double clicking and it opens as you would expect.
But if I now navigate to a different file I can see that the on hover selection isn't now working,
If you now select a different file, the original file is opened again.
I am using a Process.Start and passing the full path to the file to the method.
The application is a fair size so here are some excerpts for a Test application I have written to look into this further
The XAML for the main window
<Window x:Class="TestPopupIssue.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">
<Canvas Margin="5" Background="Red" Width="200" Height="150" >
<Rectangle Name="rectangle1"
Canvas.Top="60" Canvas.Left="50"
Height="85" Width="60"
Fill="Black" MouseEnter="rectangle1_MouseEnter" MouseLeave="rectangle1_MouseLeave" />
<Popup x:Name="PopupWindow" PlacementTarget="{Binding ElementName=rectangle1}" Placement="Top" MouseEnter="rectangle1_MouseEnter" MouseLeave="rectangle1_MouseLeave">
<ListBox MinHeight="50" ItemsSource="{Binding Files}" MouseDoubleClick="FileList_MouseDoubleClick"`enter code here` x:Name="FileList" />
</Popup>
</Canvas>
</Window>
MainWindow.xaml.cs
public partial class MainWindow : Window
{
FileList f;
public MainWindow()
{
InitializeComponent();
f = new FileList();
f.PopulateFiles();
this.DataContext = f;
}
private void FileList_MouseDoubleClick(object sender, MouseButtonEventArgs e)
{
if (FileList.SelectedItem != null)
{
string item = FileList.SelectedItem as string;
if (item != null)
{
System.Diagnostics.Process.Start(item);
}
}
}
private void rectangle1_MouseEnter(object sender, MouseEventArgs e)
{
PopupWindow.IsOpen = true;
}
private void rectangle1_MouseLeave(object sender, MouseEventArgs e)
{
PopupWindow.IsOpen = false;
}
}
And there is a FileList class which just has a generic string list of file paths called
Files
Thanks
I have tested your Sample-Application, when your opening the File with Process.Start your Focus gets stolen by the Application that opens your File.
Somehow the ListBox in the Popup canĀ“t change their SelectedItem when the Window has lost his Focus.
Unfortunately I have not managed to get the focus back on the Window, this.SetFocus() has not worked for me.
Anyway another possible Solution would be to close the Popup when your opening the File.
private void FileList_MouseDoubleClick(object sender, MouseButtonEventArgs e)
{
if (FileList.SelectedItem != null)
{
string item = FileList.SelectedItem as string;
if (item != null)
{
System.Diagnostics.Process.Start(item);
PopupWindow.IsOpen = false;
}
}
}
this way the ListBox can update the selectedItem again.
hope this helps!
I googled regarding this question but couldn't gather any information and I was wondering if it is possible for an attached behavior to handle an attached event??
I've an event declared in a class and a behavior that I am attaching to a TextBox control, the event will be raised when a button is clicked. I added the handler for this event in my behavior and wrote the logic in the event handler, but it is not executed. So, I was wondering if it is possible for an attached behavior to handle an attached event or not?
class ResetInputEventClass
{
public static readonly RoutedEvent ResetInputEvent = EventManager.RegisterRoutedEvent("ResetInput",
RoutingStrategy.Bubble,
typeof(RoutedEventHandler),
typeof(ResetInputEventClass));
public static void AddResetInputEventHandler(DependencyObject d, RoutedEventHandler handler)
{
UIElement uie = d as UIElement;
if (uie == null)
{
return;
}
uie.AddHandler(ResetInputEventClass.ResetInputEvent, handler);
}
public static void RemoveResetInputEventHandler(DependencyObject d, RoutedEventHandler handler)
{
UIElement uie = d as UIElement;
if (uie == null)
{
return;
}
uie.RemoveHandler(ResetInputEventClass.ResetInputEvent, handler);
}
}
That is my Event class and this is how I am handling it in the behavior
public class MyBehavior : Behavior<TextBoxBase>
{
public MyBehavior()
{
// Insert code required on object creation below this point.
}
protected override void OnAttached()
{
base.OnAttached();
// Insert code that you would want run when the Behavior is attached to an object.
ResetInputEventClass.AddResetInputEventHandler(AssociatedObject, OnResetInputEvent);
}
protected override void OnDetaching()
{
base.OnDetaching();
// Insert code that you would want run when the Behavior is removed from an object.
ResetInputEventClass.RemoveResetInputEventHandler(AssociatedObject, OnResetInputEvent);
}
private void OnResetInputEvent(Object o, RoutedEventArgs e)
{
//Logic
}
}
Here is my XAML Code:
<Grid x:Name="LayoutRoot">
<StackPanel>
<TextBox Margin="5" Text="Bye" TextWrapping="Wrap" Width="150">
<i:Interaction.Behaviors>
<local:MyBehavior/>
</i:Interaction.Behaviors>
</TextBox>
<TextBox Margin="5" Text="Bye" TextWrapping="Wrap" Width="150">
<i:Interaction.Behaviors>
<local:MyBehavior/>
</i:Interaction.Behaviors>
</TextBox>
<Button Name="MyButton" Content="Save" Width="50" Height="25" Click="MyButton_Click"/>
</StackPanel>
</Grid>
and I am raising the event in the click event of my button
private void MyButton_Click(object sender, RoutedEventArgs e)
{
RoutedEventArgs eventArgs = new RoutedEventArgs(ResetInputEventClass.ResetInputEvent,e.OriginalSource);
RaiseEvent(eventArgs);
}
Your problem is simple. The textbox is registered for the event, but the parent of the textbox is raising it. Thus the handler is never called. You can change the event to make it a Tunneling event instead of Bubbling. Or you can get a handle on your textbox (give it a name and reference in code behind). And have it raise the event.
<Grid x:Name="LayoutRoot">
<StackPanel>
<TextBox Margin="5" x:Name="byeTextBox" Text="Bye" TextWrapping="Wrap" Width="150">
<i:Interaction.Behaviors>
<local:MyBehavior/>
</i:Interaction.Behaviors>
</TextBox>
<Button Name="MyButton" Content="Save" Width="50" Height="25" Click="MyButton_Click"/>
</StackPanel>
</Grid>
Your code-behind should then look like this
private void MyButton_Click(object sender, RoutedEventArgs e)
{
RoutedEventArgs eventArgs = new RoutedEventArgs(ResetInputEventClass.ResetInputEvent,e.OriginalSource);
byeTextBox.RaiseEvent(eventArgs);
}
and that should fix your problem.
Of course it is possible. Show me your XAML and I ll tel you how an attached event triggers an attached behavior.
Edited:
I dont see the need why you using attached behavior and attached events because you could do everything in code behind.
Here is how to do everything in code behind:
Here is XAML without attached properties:
<Grid>
<StackPanel>
<TextBox x:Name="txtBox" Margin="5" Text="Bye" TextWrapping="Wrap" Width="150"/>
<Button Name="MyButton" Content="Save" Width="50" Height="25" Click="MyButton_Click"/>
</StackPanel>
</Grid>
This is code behind.
public MainWindow()
{
InitializeComponent();
}
private void MyButton_Click(object sender, RoutedEventArgs e)
{
this.txtBox.Text = "hello";
}
Because you have set Name property on TextBox and Button you can access them from code behind in your Window.cs and you can write your handler easly.
Here is how you can do everything with attached properties:
This is the new XAML for the solution with attached properties. I had to create my custom Interaction because the one you are using is Expression Blend or silverlight and not pure WPF.
<Grid x:Name="LayoutRoot">
<StackPanel i:Interaction.Behaviour="True">
<TextBox x:Name="txtBox" Margin="5" Text="Bye" TextWrapping="Wrap" Width="150"/>
<Button Name="MyButton" Content="Save" Width="50" Height="25" Click="MyButton_Click"/>
</StackPanel>
</Grid>
I had to set Behavior on True because the default value is false and when value is not equal to the old then the propery changed event will be called with my custom logic like this:
private void MyButton_Click(object sender, RoutedEventArgs e)
{
RoutedEventArgs eventArgs = new RoutedEventArgs(ResetInputEventClass.ResetInputEvent,e.OriginalSource);
RaiseEvent(eventArgs);
}
public class Interaction : DependencyObject
{
// Using a DependencyProperty as the backing store for Behaviour. This enables animation, styling, binding, etc...
public static readonly DependencyProperty BehaviourProperty =
DependencyProperty.RegisterAttached("Behaviour", typeof(bool), typeof(Interaction), new PropertyMetadata(false, new PropertyChangedCallback(OnBehaviourChanged)));
private static void OnBehaviourChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
StackPanel sp = (StackPanel)d;
sp.Dispatcher.BeginInvoke(new Action(() =>
{
TextBox tb = VisualTreeHelper.GetChild(sp, 0) as TextBox;
ResetInputEventClass.AddResetInputHandler(sp, new RoutedEventHandler((o, a) =>
{
// Do here whatever you want, call your custom expressions.
tb.Text = "hello";
}));
}), System.Windows.Threading.DispatcherPriority.Background);
}
}
Inside property changed event which will be called as I already mentioned when I change false to true. I wait till everything is intialized by telling the dispatcher to execute my code when application is in background. Then I find the TextBox and inject the handler which will be called when you trigger ResetInput event.
This is very complicated solution but it will work with attached events and attached properties.
I highly recommend you to use the code behind for this scenario.
Also you made a mistake inside your ResetInputEventClass class. Add and Remove methods are not correctly spelled.
This is how you should have written them:
public static void AddResetInputHandler(DependencyObject d, RoutedEventHandler handler)
{
UIElement uie = d as UIElement;
if (uie == null)
{
return;
}
uie.AddHandler(ResetInputEventClass.ResetInputEvent, handler);
}
public static void RemoveResetInputHandler(DependencyObject d, RoutedEventHandler handler)
{
UIElement uie = d as UIElement;
if (uie == null)
{
return;
}
uie.RemoveHandler(ResetInputEventClass.ResetInputEvent, handler);
}
Have fun, I hope I helped you out.
You could also have achieved this with Commands
Here is a setup: I have a textbox with a numberic value. According to the requirements every time anybody changes that value an accompanying comment needs to be provided. So visually there must be another textbox for the comment that should be displayed right next to the first one. Ideally the comment textbox needs to be placed in a callout that originates from the value textbox and displayed on the right from it overlaying anything what's underneath of it just like on this picture:
I know how to do easily it in CSS and HTML.
I have to do the same in Silverlight now.
Unfortunately I am not very strong in it, so what I am specifically asking about is how having 2 textboxes make one of them appear next to another (on the right overlaying whatever controls are underneath it) with as less XAML and code as possible.
Use a ToolTip, and set the Placement such that it appears to the right. in XAML, you can template your ToolTip to look however you want, even if that means mimicking the TextBox appearance.
This is the purpose of the ToolTip, and I feel strongly that you should always use the right tool for the right job. :)
I hope this helps. Let us know if you need code samples.
EDIT: Added the following code samples:
<TextBox ToolTipService.Placement="Right">
<ToolTipService.ToolTip>
<TextBox Text="{Binding CalloutText, Mode=OneWay}" IsReadOnly="True"/>
</ToolTipService.ToolTip>
</TextBox>
Ok, I ended up writing my own behaviour
namespace MyNamespace
{
public class CommentBehavior : Behavior<TextBox>
{
private readonly TimeSpan howLongWeWaitBeforePopupCloses = TimeSpan.FromMilliseconds(200);
private DispatcherTimer popupClosingTimer;
public static DependencyProperty PopupProperty = DependencyProperty.Register("Popup", typeof(Popup), typeof(CommentBehavior), new PropertyMetadata(null));
public Popup Popup
{
get { return (Popup)this.GetValue(PopupProperty); }
set { this.SetValue(PopupProperty, value); }
}
protected override void OnAttached()
{
this.popupClosingTimer = new DispatcherTimer();
this.popupClosingTimer.Stop();
this.popupClosingTimer.Interval = howLongWeWaitBeforePopupCloses;
this.popupClosingTimer.Tick += this.ClosePopup;
this.AssociatedObject.GotFocus += this.GotFocus;
this.AssociatedObject.LostFocus += this.LostFocus;
this.Popup.Child.GotFocus += PopupChild_GotFocus;
this.Popup.Child.LostFocus += PopupChild_LostFocus;
}
private void PopupChild_LostFocus(object sender, RoutedEventArgs e)
{
this.popupClosingTimer.Start();
}
private void PopupChild_GotFocus(object sender, RoutedEventArgs e)
{
this.popupClosingTimer.Stop();
}
protected override void OnDetaching()
{
this.AssociatedObject.GotFocus -= this.GotFocus;
this.AssociatedObject.LostFocus -= this.LostFocus;
this.Popup.GotFocus -= PopupChild_GotFocus;
this.popupClosingTimer.Tick -= this.ClosePopup;
this.popupClosingTimer = null;
}
private void ClosePopup(object sender, EventArgs e)
{
this.Popup.IsOpen = false;
this.popupClosingTimer.Stop();
}
protected void GotFocus(object sender, RoutedEventArgs e)
{
this.popupClosingTimer.Stop();
this.Popup.IsOpen = true;
var at = this.CalculatePopupPosition();
this.Popup.HorizontalOffset = at.X;
this.Popup.VerticalOffset = at.Y;
}
private Point CalculatePopupPosition()
{
var owner = this.AssociatedObject;
var transformation = owner.TransformToVisual(Application.Current.RootVisual);
var at = transformation.Transform(new Point(owner.ActualWidth, 0));
return at;
}
protected void LostFocus(object sender, RoutedEventArgs e)
{
this.popupClosingTimer.Start();
}
}
}
And the following XAML
<Grid x:Name="LayoutRoot" Background="White">
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<StackPanel Grid.Row="0" Background="Red">
<TextBox Width="200" Text="0.01">
<i:Interaction.Behaviors>
<local:CommentBehavior>
<local:CommentBehavior.Popup>
<Popup>
<TextBox Text="Comment" />
</Popup>
</local:CommentBehavior.Popup>
</local:CommentBehavior>
</i:Interaction.Behaviors>
</TextBox>
</StackPanel>
</Grid>
I ve a list from sharepoint and i collect from this list an hyperlink.
As i want my textbox to be like an hyperlink I ve added an event on mousedown to open this hyperlink, My concern is how to collect this hyperlink in the codebehind with the sender.
For the moment I've just hide this hyperlink in the tooltip maybe i can manage this differently any suggestion will be grantly appreciated.
My point so far, i don't know how to get this tooltip in the code behind.
Thanks
My XAML Code :
<ListBox Name="ListboxTips" ItemsSource="{Binding}" ScrollViewer.HorizontalScrollBarVisibility="Disabled">
<ListBox.ItemTemplate>
<DataTemplate>
<Grid>
<StackPanel Orientation="Horizontal">
<Image Source="{Binding Path=Picture}" Height="20"></Image>
<TextBlock MouseDown="TextBlock_MouseDown_URL" TextDecorations="Underline"
Margin="10,10,20,10" Width="160" TextWrapping="Wrap"
Text="{Binding Path=TitleTip}"
ToolTip="{Binding Path=URL}"/>
</StackPanel>
</Grid>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
My code behind :
foreach (SPSClient.ListItem item in TipsList)
{
var tips = new Tips();
tips.TitleTip = item.FieldValues.Values.ElementAt(1).ToString();
tips.App = item.FieldValues.Values.ElementAt(4).ToString();
// get the Hyperlink field URL value
tips.URL = ((FieldUrlValue)(item["LinkDoc"])).Url.ToString();
//should collect the description of the url
//tips.URLdesc = ((FieldUrlValue)(item["LinkDoc"])).Description.ToString();
tips.Picture = item.FieldValues.Values.ElementAt(4).ToString();
colTips.Add(tips);
}
ListboxTips.DataContext = colTips;
....
private void TextBlock_MouseDown_URL(object sender, System.Windows.Input.MouseButtonEventArgs e)
{
//string test = (ToolTip)(sender as Control).ToString();
System.Diagnostics.Process.Start("http://www.link.com");
//System.Diagnostics.Process.Start(test);
}
Thanks a lot,
You can just access the property directly. It is not elegant, but will work!
private void TextBlock_MouseDown_URL(object sender, MouseButtonEventArgs e)
{
TextBlock txtBlock = sender as TexBlock;
// just access the property
string url = txtBlock.ToolTip as string;
}
A more elegant approach might be to use a Button, Hyperlink or something that exposes a Command, so that you can bind the 'click' action to a command on your view model that performs the action you wish to execute.
usually you stick any data you want to trespass somewhere to Tag attribute.
<TextBlock .. Tag="{Binding Path=URL}" />
This is easily retrievable as a public property:
private void TextBlock_MouseDown_URL(object sender, System.Windows.Input.MouseButtonEventArgs e)
{
var tb = sender as TextBlock;
if(tb != null)
{
var neededUrl = tb.Tag;
}
}
In my application got one sidebar, which is holding this two component :
<Grid x:Name="AF" Visibility="Visibility">
<betata:AForm Height="508" VerticalAlignment="Top"/>
</Grid>
<Grid x:Name="AR" Visibility="Collapsed">
<betata:AReg Height="508" VerticalAlignment="Top"/>
</Grid>
in the AForm got hyperlink button with this method :
private void HyperlinkButton_Click(object sender, RoutedEventArgs e)
{
betata.Views.Sidebar.Sidebar sd = new Sidebar();
sd.showAR(this);
}
back to my sidebar code got another method called showAR with these function :
public void showAR(AForm aForm)
{
this.AR.Visibility = Visibility.Visible;
aForm.Visibility = Visibility.Collapsed;
}
but i not sure why the aForm will collapsed but AR could not become visible.
I would refactor this a bit, to make it more simple (which might help to solve your problem).
<Grid>
<betat:AForm x:Name="aForm" Height="508" VerticalAlignment="Top" Visibility="Visible" />
<betata:AReg x:Name="aReg" Height="508" VerticalAlignment="Top" Visibility="Collapsed" />
</Grid>
public void showAR() // this is in the code behind (xaml.cs) of the Sidebar UserControl
{
this.aReg.Visibility = Visibility.Visible;
this.aForm.Visibility = Visibility.Collapsed;
}
or you don't even need the ShowAR() and could just set the visibility in the button click, unless you're reusing the function in other places.Example:
private void HyperlinkButton_Click(object sender, RoutedEventArgs e)
{
betata.Views.Sidebar.Sidebar sd = new Sidebar();
sd.aReg.Visibility = Visibility.Visible;
sd.aForm.Visibility = Visibility.Collapsed;
}
Question had been answer in this post. Visibility of User Control can be solve via tunnelling and bubbling. which are new routing events function of silverlight