In this
example, we use data binding and bind a slider with a text. When we play with
slider, the text will change.
App Name: DataBSlider
Actually, this
task can be accomplished without using C#. Once we create a slide and textbox,
we can bind them in XAML. Add the
following lines in your XAML file to achieve this.
<Slider x:Name="mySlider1"
HorizontalAlignment="Left" Margin="54,223,0,0" VerticalAlignment="Top" Width="318" Value="50" Minimum="0" Maximum="100"
/>
<TextBlock HorizontalAlignment="Left" Margin="143,125,0,0" TextWrapping="Wrap" Text="{Binding
Value, ElementName=mySlider1, StringFormat=F1}"
VerticalAlignment="Top" Height="28" Width="173"/>
Now, you
should have an app with a textbox whose value is controlled with a slide bar as
shown in figure 1
Figure 1
However, we
want to bind the slider to an integer since we can do a lot more this way. We are
going to create two properties: sliderValue and sliderText. sliderText will be
the property related to text box and sliderValue will be associated with the value
coming from the slider. To do that, in XAML we use the following:
<Slider x:Name="mySlider1"
HorizontalAlignment="Left" Margin="54,223,0,0" VerticalAlignment="Top" Width="318" Value="{Binding sliderValue, Mode=TwoWay}" Minimum="0" Maximum="100" />
<TextBlock HorizontalAlignment="Left" Margin="143,125,0,0" TextWrapping="Wrap" Text="{Binding
sliderText, Mode=TwoWay}"
VerticalAlignment="Top" Height="28" Width="173"/>
And here’s
how my mainpage.xaml.cs looks like:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using DataBSlider.Resources;
using System.ComponentModel;
namespace DataBSlider
{
public class DataControls : INotifyPropertyChanged
{
public string sliderText
{
get { return Convert.ToString(sliderValue); }
}
public int _sliderValue;
public int sliderValue
{
get { return _sliderValue; }
set { _sliderValue=value; Notify("sliderText"); Notify("sliderValue"); }
}
public event PropertyChangedEventHandler PropertyChanged;
public void Notify(string propName)
{
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs(propName));
}
}
public partial class MainPage : PhoneApplicationPage
{
//
Constructor
DataControls myData;
public MainPage()
{
InitializeComponent();
Loaded += MainPage_Loaded;
}
void MainPage_Loaded(object sender, RoutedEventArgs e)
{
myData = new DataControls();
myData.sliderValue = 20;
ContentPanel.DataContext = myData;
}
}
}
The code
works! I get a similar output as before but since I used an integer, the value
is read as an integer. Image 2 shows my output for the code
Figure 2
0 comments:
Post a Comment