I have following code:
<ListBox x:Name="listbox1" HorizontalAlignment="Left" Height="240" Margin="81,80,0,0" VerticalAlignment="Top" Width="321" BorderBrush="#FF6C6C6C" SelectionMode="Single"/>
<ListBox x:Name="listbox2" HorizontalAlignment="Left" Height="240" Margin="482,80,0,0" VerticalAlignment="Top" Width="318" BorderBrush="#FF6C6C6C" SelectionMode="Multiple"/>
<Button x:Name="uButton" Content="Upload stuff" HorizontalAlignment="Left" Margin="840,178,0,0" VerticalAlignment="Top" Width="160" Height="46" BorderBrush="#FF6C6C6C" Foreground="#FF0068FF" Click="ButtonClick">
...
</Button>
I want the button uButton to be disabled by using IsEnable = false, until the user selected one Item from listbox1 and one or more Items from listbox2.
How can I achieve this?
Providing you use the MVVM pattern (which you should with WPF), you should implement an ICommand and bind it to the Command Property of your button. In the CanExecute method of your button you can check the Count of the selected Items of your ListBoxes. It automatically enables/disables your button when the criteria are met. This could look something like this:
public class SomeCommand: ICommand
{
#region Fields
MainWindow mainWindow;
#endregion
#region Constructors and Destructors
public SomeCommand( MainWindow mw )
{
this.mainWindow = mw;
}
#endregion
#region ICommand
public event EventHandler CanExecuteChanged
{
add { CommandManager.RequerySuggested += value; }
remove { CommandManager.RequerySuggested -= value; }
}
public bool CanExecute( object parameter )
{
return ( this.mainWindow.listbox1.SelectedItems.Count != 0
&& this.mainWindow.listbox2.SelectedItems.Count != 0 );
}
public void Execute( object parameter )
{
//DO STUFF;
}
#endregion
}
And in your XAML:
<ListBox x:Name="listbox1" HorizontalAlignment="Left" Height="240" Margin="81,80,0,0" VerticalAlignment="Top" Width="321" BorderBrush="#FF6C6C6C" SelectionMode="Single"/>
<ListBox x:Name="listbox2" HorizontalAlignment="Left" Height="240" Margin="482,80,0,0" VerticalAlignment="Top" Width="318" BorderBrush="#FF6C6C6C" SelectionMode="Multiple"/>
<Button x:Name="uButton" Command="{Binding SomeCommand}" Content="Upload stuff" HorizontalAlignment="Left" Margin="840,178,0,0" VerticalAlignment="Top" Width="160" Height="46" BorderBrush="#FF6C6C6C" Foreground="#FF0068FF" />
Add SelectionChanged="ListBox_SelectionChanged" into your listbox1 and listbox2 properties in your xaml code.
add IsEnabled="False" into your buttons properties
then in your code
private void ListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
if (listbox1.SelectedItem != null && listbox2.SelectedItems != null)
ubutton.IsEnabled = true;
else
ubutton.IsEnabled = false;
}
Related
I have a button Clear filters. I want the button click event to happen dynamically when the screen loads.
<Button Margin="10,0" CommandParameter="Clear_Filter" Command="{Binding ButtonClicks}" >
<StackPanel Orientation="Vertical">
<Image Source="/NextGen.Optik.UI.Presentation;component/Resources/clear_filters.png" Width="32" Height="32" Margin="0,2" />
<TextBlock Text="Clear Filters" HorizontalAlignment="Center" VerticalAlignment="Center"/>
</StackPanel>
</Button>
ViewModel:
private UICommand _buttonClicks;
public UICommand ButtonClicks
{
get
{
return _buttonClicks ?? (_buttonClicks = new UICommand(
param => ButtonClickCommand(param),
param => true
));
}
}
public void ButtonClickCommand(object parameter)
{
switch (parameter.ToString().ToLower())
{
case "clear_filter":
ClearFilter();
}
}
You didn't execute the click event or the Buttonbut the ICommand the Button is binding to. To be able to do this the view model which exposes the ICommand should be the DataContext of the view. Alternatively traverse the visual tree to find the element which has the desired view model as its DataContext:
MainWindow.xaml
<Window>
<Window.DataContext>
<ViewModel />
</Window.DataContext>
<Button Margin="10,0" CommandParameter="Clear_Filter" Command="{Binding ButtonClicks}" >
<StackPanel Orientation="Vertical">
<Image Source="/NextGen.Optik.UI.Presentation;component/Resources/clear_filters.png" Width="32" Height="32" Margin="0,2" />
<TextBlock Text="Clear Filters" HorizontalAlignment="Center" VerticalAlignment="Center"/>
</StackPanel>
</Button>
</Window>
MainWndow.xaml.cs
partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
this.Loaded += InitializeOnLoaded();
}
private void InitilaizeOnLoaded(object sender, EventArgs e)
{
(this.DataContext as ViewModel).ButtonClickCommand("clear_filter");
}
}
I'm learning WPF with MVVM pattern. My app is counting Body Mass Index, so it's really simple - just to help me understand the foundations of this pattern.
I was experimenting a little bit and decided to implement TextChanged event via Commands to allow user see changes in overall BMI label while he's typing a height or weight.
My textBoxes in which I use the TextChanged command are binded to ViewModel properties in TwoWay mode, so I thought that if I raise INotifyPropertyChanged event on properties binded to these textBoxes when TextChanged event occurs it will automatically update View, but it doesn't.
So question is, what am I doing wrong and how can I implement it properly?
PS. Everything else excepting View update is working (command is used, I checked with breakpoint it just doesn't change the View)
Thanks in advance
CustomCommand class:
public class CustomCommand : ICommand
{
Action<object> action;
Predicate<object> predicate;
public CustomCommand(Action<object> execute, Predicate<object> canExecute)
{
action = execute;
predicate = canExecute;
}
public event EventHandler CanExecuteChanged
{
add
{
CommandManager.RequerySuggested += value;
}
remove
{
CommandManager.RequerySuggested -= value;
}
}
public bool CanExecute(object parameter)
{
if (predicate(parameter))
return true;
else
return false;
}
public void Execute(object parameter)
{
action(parameter);
}
}
One of two textBoxes:
<TextBox HorizontalAlignment="Left" Height="23" Margin="148,83,0,0" TextWrapping="Wrap" Text="{Binding Person.Weight, Mode=TwoWay}" VerticalAlignment="Top" Width="76">
<i:Interaction.Triggers>
<i:EventTrigger EventName="TextChanged">
<i:InvokeCommandAction Command="{Binding Path=textChangedCommand}"></i:InvokeCommandAction>
</i:EventTrigger>
</i:Interaction.Triggers>
</TextBox>
And ViewModel, where TextChanged method is passed to a command
public class MainWindowViewModel : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
public void OnPropertyChanged(string propertyName)
{
PropertyChangedEventHandler propertyChanged = PropertyChanged;
if (propertyChanged != null)
propertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
public ICommand textChangedCommand { get; set; }
//public List<float> BMI_Changed;
private PersonInfo person;
public PersonInfo Person
{
get
{
return person;
}
set
{
person = value;
OnPropertyChanged("Person");
}
}
public MainWindowViewModel()
{
//BMI_Changed = new List<float>();
textChangedCommand = new CustomCommand(TextChanged, CanBeChanged);
person = Data.personInfo;
}
private void TextChanged(object obj)
{
OnPropertyChanged("BMI");
OnPropertyChanged("Weight");
OnPropertyChanged("Height");
}
private bool CanBeChanged(object obj)
{
return true;
}
}
Rest of my View code, for general overview:
<Window x:Class="SportCalculators_MVVM.MainWindow"
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"
xmlns:local="clr-namespace:SportCalculators_MVVM"
xmlns:enum="clr-namespace:SportCalculators_MVVM.Model"
xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"
mc:Ignorable="d"
Title="MainWindow" Height="340.278" Width="260.256" Loaded="Window_Loaded"
DataContext="{Binding Source={StaticResource viewModelLocator}, Path=mainWindowViewModel}">
<Grid x:Name="grid">
<Slider x:Name="mass" HorizontalAlignment="Right" Margin="0,128,58,0" VerticalAlignment="Top" Width="155" Value="{Binding Person.Weight, Mode=TwoWay}" Maximum="150" Minimum="20"/>
<Slider x:Name="height" HorizontalAlignment="Left" Margin="40,210,0,0" VerticalAlignment="Top" Width="155" Minimum="100" Maximum="230" Value="{Binding Person.Height, Mode=TwoWay}"/>
<RadioButton x:Name="sex" Content="Kobieta" HorizontalAlignment="Left" Margin="45,41,0,0" VerticalAlignment="Top" IsChecked="{Binding Person.Sex, Converter={StaticResource ResourceKey=genderConverter}, ConverterParameter={x:Static enum:Sex.Female}}"/>
<RadioButton x:Name="sex1" Content="Mężczyzna" HorizontalAlignment="Left" Margin="150,41,0,0" VerticalAlignment="Top" IsChecked="{Binding Person.Sex, Converter={StaticResource ResourceKey=genderConverter}, ConverterParameter={x:Static enum:Sex.Male}}"/>
<Label x:Name="massLabel" Content="Waga" HorizontalAlignment="Left" Margin="40,80,0,0" VerticalAlignment="Top"/>
<Label x:Name="heightLabel" Content="Wzrost" HorizontalAlignment="Left" Margin="39,167,0,0" VerticalAlignment="Top"/>
<Label x:Name="label" Content="{Binding Person.BMI}" HorizontalAlignment="Left" Margin="39,274,0,0" VerticalAlignment="Top"/>
<Button Content="Statystyki" HorizontalAlignment="Left" Margin="149,274,0,0" VerticalAlignment="Top" Width="75" RenderTransformOrigin="0.325,-0.438"/>
<TextBox HorizontalAlignment="Left" Height="23" Margin="148,83,0,0" TextWrapping="Wrap" Text="{Binding Person.Weight, Mode=TwoWay}" VerticalAlignment="Top" Width="76">
<i:Interaction.Triggers>
<i:EventTrigger EventName="TextChanged">
<i:InvokeCommandAction Command="{Binding Path=textChangedCommand}"></i:InvokeCommandAction>
</i:EventTrigger>
</i:Interaction.Triggers>
</TextBox>
<TextBox HorizontalAlignment="Left" Height="23" Margin="148,170,0,0" TextWrapping="Wrap" Text="{Binding Person.Height, Mode=TwoWay}" VerticalAlignment="Top" Width="76">
<i:Interaction.Triggers>
<i:EventTrigger EventName="TextChanged">
<i:InvokeCommandAction Command="{Binding Path=textChangedCommand}"></i:InvokeCommandAction>
</i:EventTrigger>
</i:Interaction.Triggers>
</TextBox>
</Grid>
Ed Plunkett gave the simplest solution:
There is no need to write whole bunch of code to implement command while TextChanged occurs, there is a Binding property UpdateSourceTrigger which determines when there should be the update, by default it's set to LostFocus so it is for example when you click on another control, if you'd like to update it while user is typing, you need to set value to PropertyChanged and that's it!
<TextBox Text="{Binding Person.Weight, UpdateSourceTrigger=PropertyChanged}">
I am a newbie in WPF, I have a problem concern binding two different ViewModels to two UserControls
that will be attached to two Tabpages in a Tabcontrol.
My code snippets are as follows:
MainWindow.xaml
<Window.Resources>
<local:UserControl1Model x:Key="Control1Model" />
<local:UserControl2Model x:Key="Control2Model" />
</Window.Resources>
<Grid HorizontalAlignment="Left" Height="330" VerticalAlignment="Top" Width="592">
<Grid HorizontalAlignment="Left" Height="45" Margin="0,330,-1,-45" VerticalAlignment="Top" Width="593">
<Button Content="Button" HorizontalAlignment="Left" Margin="490,5,0,0" VerticalAlignment="Top" Width="75" Click="Button_Click"/>
</Grid>
<TabControl HorizontalAlignment="Left" Height="330" VerticalAlignment="Top" Width="592" >
<TabItem x:Name="UserControl1TabItem" Header="User Control 1" >
<Grid x:Name="UserControl1Tabpage" Background="#FFE5E5E5" Margin="0,0,-4,-2" Height="300" VerticalAlignment="Top" IsEnabled="true" >
<local:UserControl1 VerticalAlignment="Top" DataContext="{Binding Source={StaticResource Control1Model}}" />
</Grid>
</TabItem>
<TabItem x:Name="UserControl2TabItem" Header="User Control 2">
<Grid x:Name="UserControl2Tabpage" Background="#FFE5E5E5">
<local:UserControl2 VerticalAlignment="Top" DataContext="{Binding Source={StaticResource Control2Model}}" />
</Grid>
</TabItem>
</TabControl>
</Grid>
MainWindow.xaml.cs
public partial class MainWindow : Window
{
private UserControl1Model _userControl1Model = new UserControl1Model();
private UserControl2Model _userControl2Model = new UserControl2Model();
public MainWindow()
{
InitializeComponent();
_userControl1Model.Message = "Hello";
_userControl2Model.Message = "Test";
}
private void Button_Click(object sender, RoutedEventArgs e)
{
// Will do something
}
}
UserControl1Model.cs
public class UserControl1Model : INotifyPropertyChanged
{
private string _message;
public string Message
{
get { return _message; }
set
{
_message = value;
OnPropertyChanged("Message");
}
}
public UserControl1Model()
{
}
// Create the OnPropertyChanged method to raise the event
protected void OnPropertyChanged(string message)
{
var handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(message));
}
}
#region INotifyPropertyChanged Members
// Declare the event
public event PropertyChangedEventHandler PropertyChanged;
#endregion
}
For trying purpose, the content of UserControl2Model.cs is as same as UserControl1Model.cs
UserControl1.xaml
<UserControl.Resources>
<app:UserControl1Model x:Key="Control1Model" />
</UserControl.Resources>
<Grid Margin="0,0,0,42" DataContext="{Binding Source={StaticResource Control1Model}}">
<Label Content="Test:" HorizontalAlignment="Left" Margin="48,57,0,0" VerticalAlignment="Top" Width="47"/>
<TextBox x:Name="Conrol1ModelTextbox" HorizontalAlignment="Left" Height="23" Margin="90,59,0,0" TextWrapping="Wrap"
Text="{Binding Message, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"
VerticalAlignment="Top" Width="466" />
</Grid>
UserControl1.xaml.cs
public partial class UserControl1 : UserControl
{
public UserControl1()
{
InitializeComponent();
}
}
UserControl2.xaml
<UserControl.Resources>
<app:UserControl2Model x:Key="Control2Model" />
</UserControl.Resources>
<Grid Margin="0,0,0,42" DataContext="{Binding Source={StaticResource Control2Model}}">
<Label Content="Test:" HorizontalAlignment="Left" Margin="48,57,0,0" VerticalAlignment="Top" Width="47"/>
<TextBox x:Name="Conrol2ModelTextbox" HorizontalAlignment="Left" Height="23" Margin="90,59,0,0" TextWrapping="Wrap"
Text="{Binding Message, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"
VerticalAlignment="Top" Width="466" />
</Grid>
For trying purpose, the content of UserControl2.xaml.cs is as same as UserControl1.xaml.cs
My problem is the initial values, "Hello" and "Test" for the two user controls, which are initialized in MainWindow.xaml.cs cannot
be "binded" into the user controls textboxes. What am I doing wrong or missing?
When you declare resources like this
<Window.Resources>
<local:UserControl1Model x:Key="Control1Model" />
<local:UserControl2Model x:Key="Control2Model" />
</Window.Resources>
You are actually constructing new instances of UserControl1Model and UserControl2Model instead using the ones you declared in MainWindow.cs
Also you are not creating any ViewModel for the MainWindow. You should create a MainWindowViewModel like such
public class MainWindowViewModel : INotifyPropertyChanged
{
public ViewModelLocator
{
this.FirstModel= new UserControl1Model
{
Message = "Hello";
}
this.SecondModel = new UserControl2Model
{
Message = "Test";
}
}
private UserControl1Model firstModel
public UserControl1Model FirstModel
{
get
{
return this.firstModel;
}
set
{
this.firstModel= value;
OnPropertyChanged("FirstModel");
}
}
// Same for the UserControl2Model
// implementation of the INotifyPropertyChanged
}
Also you would need to set the DataContext for the MainWindow.
public MainWindow()
{
InitializeComponent();
this.DataContext = new MainWindowViewModel();
}
And remove the resources from the UserControl xamls. You are already defining the DataContext in the MainWindow.xaml but the binding should be bound from the MainWindowViewModel as such.
<local:UserControl1 VerticalAlignment="Top" DataContext="{Binding FirstModel}" />
Create a ViewModelLocator. you can find various sites on the internet for this subject.
a simple one would be:
public class ViewModelLocator
{
public UserControl1Model UserControl1Model { get; set; } = new UserControl1Model();
public UserControl2Model UserControl2Model { get; set; } = new UserControl2Model();
public ViewModelLocator
{
UserControl1Model.Message = "Hello";
UserControl2Model.Message = "Test";
}
}
then you can use it in your views
<UserControl.Resources>
<app:ViewModelLocator x:Key="ViewModelLocator" />
</UserControl.Resources>
<Grid Margin="0,0,0,42" DataContext="{Binding UserControl2Model Source={StaticResource ViewModelLocator}}">
<Label Content="Test:" HorizontalAlignment="Left" Margin="48,57,0,0" VerticalAlignment="Top" Width="47"/>
<TextBox x:Name="Conrol2ModelTextbox" HorizontalAlignment="Left" Height="23" Margin="90,59,0,0" TextWrapping="Wrap"
Text="{Binding Message, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"
VerticalAlignment="Top" Width="466" />
</Grid>
Suppose, I create this instance in the xaml as follows: <Window.Resources> <local:MainWindowViewModel x:Key="MainWindowViewModel" /> </Window.Resources> instead of creating inside MainWindow.xaml.cs. Then, how can I reference this instance inside MainWindow.xaml.cs, e.g. to get value from MainWindowViewModel.ViewModelLocator.FirstModel.Message ?
Like this:
MainWindowViewModel viewModel = this.Resources["MainWindowViewModel"] as MainWindowViewModel;
//access any properties of viewModel here...
I have a gridview in UWP app and I have put a button in each gridview item in datatemplate so that it can be used to delete/remove that specific item from the gridview ( removing it from observableCollection behind). I am not using MVVM approach, because I am not much familiar with it, I am using a normal Observable Collection for binding of data and data template.
if you can suggest me a better way to do it, myabe using MVVM please suggest me how to do it. Thanks in advance
Code :
XAML GRID VIEW (button with the red back ground is the button I wanna use to delete item)
<controls:AdaptiveGridView Name="HistoryGridView" StretchContentForSingleRow="False"
Style="{StaticResource MainGridView}"
ItemClick ="HistoryGridView_SelectionChanged"
ItemsSource="{x:Bind HistoryVideos, Mode=OneWay}">
<controls:AdaptiveGridView.ItemTemplate>
<DataTemplate x:DataType="data:Video">
<StackPanel Margin="4" >
<Grid>
<Button Background="Red"
HorizontalAlignment="Right" VerticalAlignment="Top"
Height="36" Canvas.ZIndex="1"
Style="{StaticResource TransparentButton}" Width="36">
<fa:FontAwesome Icon="Close" FontSize="20" HorizontalAlignment="Center" Foreground="White"
/>
</Button>
<Image Canvas.ZIndex="0" Source="{x:Bind Thumbnail}" Style="{StaticResource GridViewImage}"/>
<Border Style="{StaticResource TimeBorder}" Height="Auto" VerticalAlignment="Bottom"
Canvas.ZIndex="1"
HorizontalAlignment="Left">
<TextBlock Text="{x:Bind Duration}" Foreground="White" Height="Auto"/>
</Border>
</Grid>
<TextBlock Text="{x:Bind Name}" Style="{StaticResource GridViewVideoName}"/>
<TextBlock Text="{x:Bind ParentName}" Style="{StaticResource GridViewParentName}"/>
<StackPanel Orientation="Horizontal" HorizontalAlignment="Stretch">
<TextBlock Text="{x:Bind Views}" Style="{StaticResource GridViewViews}"/>
<TextBlock Text="Views" HorizontalAlignment="Right"/>
</StackPanel>
</StackPanel>
</DataTemplate>
</controls:AdaptiveGridView.ItemTemplate>
</controls:AdaptiveGridView>
Code Behind
public History()
{
this.InitializeComponent();
HistoryVideos = new ObservableCollection<Video>();
}
public ObservableCollection<Video> HistoryVideos { get; private set; }
I am using onnavigated to method for filling the collection and it works fine and also I guess that is not relevent here.
We can add the Command to the Button to invoke when this button is pressed and we can use parameter to pass to the Command property.
To use the Command, we should be able to define a DelegateCommand class that inherits from the ICommand.
For example:
internal class DelegateCommand : ICommand
{
private Action<object> execute;
private Func<object, bool> canExecute;
public DelegateCommand(Action<object> execute)
{
this.execute = execute;
this.canExecute = (x) => { return true; };
}
public DelegateCommand(Action<object> execute, Func<object, bool> canExecute)
{
this.execute = execute;
this.canExecute = canExecute;
}
public bool CanExecute(object parameter)
{
return canExecute(parameter);
}
public event EventHandler CanExecuteChanged;
public void RaiseCanExecuteChanged()
{
if (CanExecuteChanged != null)
{
CanExecuteChanged(this, EventArgs.Empty);
}
}
public void Execute(object parameter)
{
execute(parameter);
}
}
We can add the Id property in the Video, then we can pass the Id property to the CommandParameter. When we click the Button, the ExecuteDeleteCommand method will be fired. We can use the Id to find the Video in the HistoryVideos and use the Remove method to remove it.
The ViewModel code:
internal class ViewModel
{
private ObservableCollection<Viedo> _videos;
public ObservableCollection<Viedo> Videos
{
get
{
return _videos;
}
set
{
if (_videos != value)
{
_videos = value;
}
}
}
public ICommand DeleteCommand { set; get; }
private void ExecuteDeleteCommand(object param)
{
int id = (Int32)param;
Viedo cus = GetCustomerById(id);
if (cus != null)
{
Videos.Remove(cus);
}
}
private Viedo GetCustomerById(int id)
{
try
{
return Videos.First(x => x.Id == id);
}
catch
{
return null;
}
}
public ViewModel()
{
Videos = new ObservableCollection<Viedo>();
for (int i = 0; i < 5; i++)
{
Videos.Add(new Viedo());
Videos[i].Name = "Name";
Videos[i].Id = i;
}
this.DeleteCommand = new DelegateCommand(ExecuteDeleteCommand);
}
}
The XAML code:
<GridView Name="MyGridView" ItemsSource="{Binding Videos}">
<GridView.ItemTemplate>
<DataTemplate>
<StackPanel>
<TextBlock Text="{Binding Name}"></TextBlock>
<Button Background="Red"
HorizontalAlignment="Right" VerticalAlignment="Top"
Height="36" Canvas.ZIndex="1"
Width="36" Command="{Binding DataContext.DeleteCommand, ElementName=MyGridView}" CommandParameter="{Binding Id}">
</Button>
</StackPanel>
</DataTemplate>
</GridView.ItemTemplate>
</GridView>
The code behind:
private ViewModel myViewModel;
public MainPage()
{
this.InitializeComponent();
myViewModel = new ViewModel();
MyGridView.DataContext = myViewModel;
}
Update:
<GridView Name="MyGridView" ItemsSource="{x:Bind myViewModel.Videos}">
<GridView.ItemTemplate>
<DataTemplate x:DataType="local:Viedo">
<StackPanel>
<TextBlock Text="{x:Bind Name}"></TextBlock>
<Button Background="Red"
HorizontalAlignment="Right" VerticalAlignment="Top"
Height="36" Canvas.ZIndex="1"
Width="36" Command="{Binding DataContext.DeleteCommand, ElementName=MyGridView}" CommandParameter="{Binding Id}">
</Button>
</StackPanel>
</DataTemplate>
</GridView.ItemTemplate>
</GridView>
I am developing my first Windows 8 app, in one page i am trying to update button text with latest timestop when page loads. I defined my xaml and codebehind like below:
I am using databinding to update the button text but it is not working as expected:
MainPage.xaml
<Grid Background="{StaticResource ApplicationPageBackgroundThemeBrush}">
<Button HorizontalAlignment="Left" Margin="333,284,0,0" VerticalAlignment="Top" Height="69" Width="162">
<Button.Resources>
<DataTemplate x:Key="DataTemplate1">
<Grid>
<TextBlock HorizontalAlignment="Left" TextWrapping="Wrap" Text="{Binding ButtonText}" VerticalAlignment="Top" Foreground="#FFFF6800" Height="34" Margin="-30,0,-22,-14" Width="115"/>
</Grid>
</DataTemplate>
</Button.Resources>
<Button.ContentTemplate>
<StaticResource ResourceKey="DataTemplate1"/>
</Button.ContentTemplate>
</Button>
</Grid>
MainPage.xaml.cs
public StatsClass Stats { get; private set; }
public MainPage()
{
this.InitializeComponent();
this.DataContext = Stats;
}
protected override void OnNavigatedTo(NavigationEventArgs e)
{
UpdateButton();
}
private void UpdateButton()
{
if (Stats == null)
Stats = new StatsClass();
Stats.ButtonText = DateTime.Now.ToString();
}
StatsClass.cs
public class StatsClass : INotifyPropertyChanged
{
private string _buttonText;
public string ButtonText
{
get
{
return _buttonText;
}
set
{
_buttonText = value;
OnPropertyChanged("ButtonText");
}
}
public event PropertyChangedEventHandler PropertyChanged;
protected void OnPropertyChanged(string name)
{
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs(name));
}
}
You have set Content of your Button twice, once with Content="Button" and again with.Button.ContentTemplate. You could just have:
<Button HorizontalAlignment="Left" Margin="333,284,0,0" VerticalAlignment="Top" Height="69" Width="162">
<Grid>
<TextBlock HorizontalAlignment="Left" TextWrapping="Wrap" Text="{Binding ButtonText}" VerticalAlignment="Top" Foreground="#FFFF6800" Height="34" Margin="-30,0,-22,-14" Width="115"/>
</Grid>
</Button>
I had a similar issue yesterday using binding in a DataTemplate. I guess that you also had a binding error in the debug output.
I solved it using a relative source like that:
<TextBlock Text={Binding DataContext.ButtonText,
RelativeSource={RelativeSource FindAncestor, AncestorType=*YourControl*}}"/>
The Template has no direct access to the datacontext. By using the relative source you can bind to its properties.