C# System.NullReferenceException during setting slider value to text property - c#

I have this simple slider project. I wanna show slider value in TextBox.
<Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
<TextBox x:Name="sliderValue" HorizontalAlignment="Stretch" VerticalAlignment="Top" />
<Slider x:Name="slider" Minimum="0" Maximum="20" Value="5" ValueChanged="slider_ValueChanged"/></Grid>
// Constructor
public MainPage()
{
InitializeComponent();
}
private void slider_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
{
var slider = sender as Slider;
string value = string.Format("{0}", slider.Value);
sliderValue.Text = value;
}
In last line I am getting this error:
System.NullReferenceException: Object reference not set to an instance of an object.
at slider_test.MainPage.slider_ValueChanged(Object sender, RoutedPropertyChangedEventArgs`1 e)
at .......
Could anyone explain me what is the problem? Thank you.

You can do it using XAML by Binding slider value to TextBlock text.
<Slider x:Name="SliderValueText" ValueChanged="SliderValueText_ValueChanged"
VerticalAlignment="Top"
Width="440"
Minimum="0"
Maximum="20"
Value="5" />
<TextBlock Height="30"
Text="{Binding Value, ElementName=SliderValueText}"
VerticalAlignment="Top"
HorizontalAlignment="Center" />
private void SliderValueText_ValueChanged(object sender, System.Windows.RoutedPropertyChangedEventArgs<double> e)
{
string value = string.Format("{0}", e.NewValue);
MessageBox.Show(value);
}
It is one of the option. Here you need the slider value. So I am storing in the variable "value". That's what I am displaying in MessageBox. But it is least case to try...

I am not sure but may be this will help you.
private void slider_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
{
Dispatcher.BeginInvoke(() =>
{
string value = string.Format("{0}", e.NewValue);
sliderValue.Text = value;
});
}

In this way use e.NewValue for polling changing a value:
private void slider_ValueChanged(object sender, RangeBaseValueChangedEventArgs e)
{
Debug.WriteLine("Value changed and value is " + e.NewValue.ToString());
}
But for labels simply use XAML bindings:
<TextBlock x:Name="someLabel"
Text="{Binding ElementName=slider, Path=Value}"
/>

Related

Slider control is not working properly

I want to change textblock value depending on the slider value each time I change it. But it shouldn't be done in XAML, because I want to make manipulations over return data. But the text in the textblock is not changed. Where is the problem?
My XAML is:
<Slider x:Name="slider" Value="0.2" SmallChange="0.1" Minimum="0" Maximum="10"
HorizontalAlignment="Left" Margin="26,208,0,0" VerticalAlignment="Top"
Width="195" ValueChanged="Slider_ValueChanged"/>
my WP 8 page code is:
private void Slider_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
{
Slider slider = e.OriginalSource as Slider;
if (slider != null)
{
sliderTBk.Text = slider.Value.ToString();
}
}
Use thi XAML without CodeBehind
<TextBlock x:Name="sliderTBk" Text="{Binding Value, ElementName=slider" />
This should work.
And dont forget to remove the ValueChanged Eventhandler.
If you have to use CodeBehind:
private void Slider_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
{
if (slider != null)
{
sliderTBk.Text = slider.Value.ToString();
}
}
Try this becuse i think that
Slider slider = e.OriginalSource as Slider;
hides your control x:name="slider"

Tap and hold Listbox Windows Phone

Does anybody know how can I add event whenever I press my listbox it will directly run my code. I need it to change my listbox selected item. This is my xaml:
<ListBox x:Name="ListNabi" SelectionChanged="ListNabi_SelectionChanged" ItemsSource="{Binding}" Tap="ListNabi_Tap" Hold="ListNabi_Hold">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Margin="5,0,5,0">
<!--<Image Source="{Binding ImageSource}" Stretch="None"/>-->
<Grid Width="480" Background="White">
<Image x:Name="listDaun" Source="/Images/Button/Button List.png"
Margin="0,5,5,5" Width="38" HorizontalAlignment="Left"></Image>
<TextBlock x:Name="namaNabi" TextWrapping="NoWrap"
Text="{Binding Name}" FontFamily="{StaticResource PhoneFontFamilyNormal}"
FontSize="36" Foreground="#00ADCE" Margin="40,5,0,5"></TextBlock>
<Rectangle Margin="0,50,0,0" Height="2" Fill="#00ADCE" Width="480"/>
</Grid>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
And in CS I did like this:
private void ListNabi_Hold(object sender, System.Windows.Input.GestureEventArgs e)
{
changeColor("#00ADCE", "#FFFFFF", "#FFFFFF", "/Images/Button/Button List1.png");
}
private void ListNabi_Tap(object sender, System.Windows.Input.GestureEventArgs e)
{
if (ListNabi.SelectedIndex != -1)
{
id = ListNabi.SelectedIndex;
}
MessageBox.Show("tes");
changeColor("#00ADCE", "#FFFFFF", "#FFFFFF", "/Images/Button/Button List1.png");
}
private void ListNabi_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
if (ListNabi.SelectedIndex != -1)
{
id = ListNabi.SelectedIndex;
changeColor("#00ADCE", "#FFFFFF", "#FFFFFF", "/Images/Button/Button List1.png");
NavigationService.Navigate(new Uri("/Pages/25_Nabi/DetailPage.xaml?id="
+ ListNabi.SelectedIndex, UriKind.Relative));
ListNabi.SelectedIndex = -1;
}
}
But it will only run my code (in this context changeColor()) whenever I hold my listbox after some time or after I release my finger. Is there any event I can use to start run my code whenever my finger start touch?
For that use the following events: ManipulationStarted, ManipulationDelta and ManipulationCompleted. You will get everything you need from positions to the number of different touch points.
You can do sophisticated things with it like dragging and pinching.

How to select an item from a listbox in windows phone?

I've a list of data,
Each row will show a data and will have a button, when i click the data shown i want give some data to the previous page and when i click the button in the same row i want to send that same data to next page.
My Xaml code,
<ListBox x:Name="List" HorizontalAlignment="Left" Height="612" Margin="6,7,0,0" VerticalAlignment="Top" Width="443" SelectionChanged="List_SelectionChanged_1">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal" Width="420" Height="50">
<TextBlock x:Name="tbName" Width="400" Height="44" FontSize="22" FontWeight="Bold" Text="{Binding Name}" />
<Button x:Name="DetailButton" Height="44" Width="20" Content=">" FontWeight="Bold" Click="DetailButton_Click_1"/>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
and the code for List_SelectionChanged_1 event handler is,
private void List_SelectionChanged_1(object sender, SelectionChangedEventArgs e)
{
Display selectedItemData = (sender as ListBox).SelectedValue as Display;
NavigationService.Navigate("/Page1.xaml",selectedItemData);
}
and my DetailButton_Click_1 event handler is,
private void DetailButton_Click_1(object sender, RoutedEventArgs e)
{
Display selectedItemData = (sender as ListBox).SelectedValue as Display;
NavigationService.Navigate("/page3.xaml", selectedItemData);
}
Things work fine for *List_SelectionChanged_1*, but i get an exception while executing
Display selectedItemData = (sender as ListBox).SelectedValue as Display;
of the DetailButton_Click_1 , i get an exception a null exception,
An exception of type 'System.NullReferenceException' occurred in ExpenseApp.DLL but was not handled in user code
What should i do make it work?
The underlying problem is that the sender of the button click event is the button, not the ListBox.
Also note that clicking the button on your data template will not necessarily select that item in the list. Try to grab the clicked item's data context and use that instead of .SelectedItem
private void DetailButton_Click_1(object sender, RoutedEventArgs e)
{
var clickedUIElement = sender as Button;
if (null == clickedUIElement) { Return; }
Display selectedItemData = clickedUIElement.DataContext as Display;
if(null != selectedItemData)
{
NavigationService.Navigate("/page3.xaml", selectedItemData);
}
}
Your code, as it stands, will have a null reference since you can't cast a Button as a ListBox.
try verify if the selectvalue is null before execute the code:
private void DetailButton_Click_1(object sender, RoutedEventArgs e)
{
If ((sender as ListBox).SelectedValue != null){
Display selectedItemData = (sender as ListBox).SelectedValue as Display;
NavigationService.Navigate("/page3.xaml", selectedItemData);
}
}

Windows 8 Store App - MediaElement no longer playing Audio

I am trying to play an audio file (.wav) when a toggle button is pressed (and pause when pressed again). I had it working initially, but now I must of messed something up and am looking for help. This is how I'm doing it:
Create MediaElement in XAML
<MediaElement x:Name="myMediaElement" HorizontalAlignment="Center" VerticalAlignment="Center" PosterSource="vuvuzela.png" IsLooping="True" Source="Assets/vuvuzela.wav" Grid.Row="1" AutoPlay="False"/>
Then My ToggleButton is this:
<ToggleButton x:Name="ToggleButton" Content="Activate" HorizontalAlignment="Center" VerticalAlignment="Center" Grid.Row="2" FontSize="32" Style="{StaticResource ToggleButtonStyle1}" Checked="Tog_Checked" Unchecked="Tog_Unchecked"/>
And in my Code-behind, I have the ToggleButton's checked/unchecked handlers:
private void Tog_Checked(object sender, RoutedEventArgs e)
{
myMediaElement.Play();
}
private void Tog_Unchecked(object sender, RoutedEventArgs e)
{
myMediaElement.Pause();
}
Any ideas as to what might be going wrong or how to check it? Thanks!
EDIT: Debugged some more. Looks like the myMediaElement is not getting past the Opening state?
Apparently it was a hardware problem. My computer (MacBook running Bootcamp) was the issue. Finally found that answer in this post --> MediaElement in WinRT / Win8 does not work at all
Thanks for all the help though everyone
Is it important to you that your media element be visual like that?
Try this in your click event instead:
var _Media = new Windows.UI.Xaml.Controls.MediaElement() { AutoPlay = false };
var _Location = Windows.ApplicationModel.Package.Current.InstalledLocation;
var _Folder = await _Location.GetFolderAsync("Assets");
var _File = await _Folder.GetFileAsync("Ding.wav");
var _Stream = await _File.OpenAsync(Windows.Storage.FileAccessMode.Read);
_Media.SetSource(_Stream, _File.ContentType);
_Media.Play();
Have shown code required to play audio file. (code for playing next audio is bonus )
1.Add media element, play/pause/stop buttons to the XAML file.
<MediaElement x:Name="media" Source="Assets/page1/para1.mp3"
Grid.Column="0" Grid.Row="0" AutoPlay="True" />
<Button Click="StopMedia" Grid.Column="0" Grid.Row="1" Content="Stop" />
<Button Click="PauseMedia" Grid.Column="1" Grid.Row="1" Content="Pause" />
<Button Click="PlayMedia" Grid.Column="2" Grid.Row="1" Content="Play" />
2.Add the following code to the code-behind file:
private void StopMedia(object sender, RoutedEventArgs e)
{
media.Stop();
}
private void PauseMedia(object sender, RoutedEventArgs e)
{
media.Pause();
}
private void PlayMedia(object sender, RoutedEventArgs e)
{
media.Source = new Uri(this.BaseUri, "Assets/page1/para1.mp3");
media.Play();
}
protected override async void LoadState(Object navigationParameter, Dictionary<String, Object> pageState)
{
media.MediaEnded += media_MediaEnded;
}
private void media_MediaEnded(object sender, RoutedEventArgs e)
{
media.Source = new Uri(this.BaseUri, "Assets/page1/para2.mp3");
media.Play();
}

How to extract value from selected TextBlock element in a ListBox?

I'm using a ListBox to display all values contained in Dictionary<> object:
<ListBox Height="519" x:Name="ContactsListBox" Width="460" Margin="0,0,0,0" SelectionChanged="ContactsListBox_SelectionChanged">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Vertical">
<TextBlock Text="{Binding Key}" Margin="5" Foreground="{StaticResource PhoneAccentBrush}"/>
<TextBlock x:Name ="LastNameData" Text="{Binding Value}" Margin="20, 0" />
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
Content is filled by the following code:
Dictionary<long, Contact> contacts = new Dictionary<long, Contact>();
this.ContactsListBox.ItemsSource = contacts;
Now, I would like to 'know' which specific "Contact" in ListBox is currently selected, either by knowing its Key, or just by extracting value from "LastNameData" TextBlock.
I tried doing something like that, but obviosly it doesn't work:
private void ContactsListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
ListBox lb = this.ContactsListBox.SelectedItem as ListBox;
this.Test_SomeOtherTextBlock.Text = lb.ToString();
}
I would really appreciate your help!
you can even do the follwing:
<ListBox Height="519" x:Name="ContactsListBox" Width="460" Margin="0,0,0,0" >
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Vertical">
<TextBlock Text="{Binding Key}" Margin="5"/>
<TextBlock x:Name ="LastNameData" Text="{Binding Value}" Margin="20, 0" />
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
<Grid DataContext="{Binding ElementName=ContactsListBox, Path=SelectedItem}" Margin="0,470,0,0">
<TextBlock Text="{Binding Value}"/>
</Grid>
So you don't need code behind...
BR,
TJ
There are several problems:
In Xaml you probably don't want to display the class name, but a reasonable string, for example:
<TextBlock x:Name ="LastNameData" Text="{Binding Value.LastName}" Margin="20, 0" />
In the selection processing the selected item is KeyValuePair<...>. You could easily find it yourself, if you looked at the returned type in debugger. (Should be kind of a reflex for a programmer, hence a questions like above should never appear :))
private void ContactsListBox_SelectionChanged(object sender, SelectionChangedEventArgs e) {
KeyValuePair<long, Contact> kv = (KeyValuePair<long, Contact>)this.ContactsListBox.SelectedItem;
Contact c = (Contact)kv.Value;
Debug.WriteLine(c.LastName);
}
Your code is good, using ListBox.SelectedItem is the right approach.
I think the problem is that you should cast it as ListBoxItem, not ListBox. And also to get to its value using DataContext, so something like along these lines (not tested, I'm not sure about accessing DataContext value in the last line):
private void ContactsListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
ListBoxItem lbi = this.ContactsListBox.SelectedItem as ListBoxItem;
var dataContext = lbi.DataContext;
this.Test_SomeOtherTextBlock.Text = dataContext.Value.ToString();
}
Try this it works for me, will help you to...
private void ListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
ListBox ContactListBox = sender as ListBox;
ListBoxItem listBoxItem = ContactListBox .ItemContainerGenerator.ContainerFromItem(ContactListBox.SelectedItem) as ListBoxItem;
if (listBoxItem == null)
{
return;
}
TextBlock txtBlock = FindVisualChildByName(listBoxItem, "ListTextBlock");
MessageBox.Show(txtBlock.Text);
}
private static T FindVisualChildByName<T>(DependencyObject parent, string name) where T : DependencyObject
{
for (int i = 0; i < VisualTreeHelper.GetChildrenCount(parent); i++)
{
var child = VisualTreeHelper.GetChild(parent, i);
string controlName = child.GetValue(NameProperty) as string;
if (controlName == name)
{
return child as T;
}
T result = FindVisualChildByName<T>(child, name);
if (result != null)
return result;
}
return null;
}
private void ContactsListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
ListBox lb = this.ContactsListBox.SelectedItem as ListBox;
this.Test_SomeOtherTextBlock.Text = lb.ToString();
}
will go something like this..
private void ContactsListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
ListBox lb = this.ContactsListBox.SelectedItem as ListBox;
DataTemplate template=lb.ContentTemplate;
//Now here you have to extract the content of the data template
and then you need to extract the TextBlock from that content.
}
This is just an overview of the functionality.Sorry not able to post complete code.

Categories

Resources