How to change Text property with ICommand C# XAML - c#

I make a simple weather app. And now i want to change it.
I want to implement a command to a button, and when is pressed, a TextBlock will update with weather info but i can't acces property of TextBlock.
Here is the Command class from Models:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Input;
namespace RemakeWindowsWeather.Models
{
public class Command : ICommand
{
public event EventHandler CanExecuteChanged;
Func<object, bool> canExecuteMethod;
Action<object> executeMethod;
public Command(Func<object, bool> canExecuteMethod, Action<object> executeMethod)
{
this.canExecuteMethod = canExecuteMethod;
this.executeMethod = executeMethod;
}
public bool CanExecute(object parameter)
{
return canExecuteMethod(parameter);
}
public void Execute(object parameter)
{
executeMethod(parameter);
}
}
}
Here is the class from ViewModels where i want to change the property of TextBlock:
using RemakeWindowsWeather.Models;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace RemakeWindowsWeather.ViewModels
{
public class CommandViewModel
{
Command ShowWeather { get; set; }
public CommandViewModel()
{
ShowWeather = new Command(canExecuteMethod, executeMethod);
}
private bool canExecuteMethod(object parameter)
{
return true;
}
private async void executeMethod(object parameter)
{
var pos = await LocationManager.GetLocation();
var lat = pos.Coordinate.Latitude;
var lon = pos.Coordinate.Longitude;
var weather = await WeatherProxyMap.GetWeather(lon, lat);
//HERE.. not working
WeatherCondition.Text = weather.main.temp + " " + weather.name;
}
}
}
Here is the XAML:
<Page
x:Class="RemakeWindowsWeather.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:RemakeWindowsWeather"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
x:Name="MyPage">
<Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
<StackPanel>
<Button Height="30"
Width="120"
Click="Button_Click"
Content="Get Weather"/>
<TextBlock Name="WeatherCondition"
Margin="0,20,0,20"/>
<TextBox Name="CitySearch"
PlaceholderText="Search for weather.."
Margin="0,20,0,20"/>
<Button Width="120"
Height="30"
Click="Button_Click_1"
Content="Get Weather"/>
<TextBlock Name="CityNameTxtBlock"/>
</StackPanel>
</Grid>

You need to bind your command from the viewmodel in xaml, instead using event handlers in the view.
<Button Width="120"
Height="30"
Command="{Binding ShowWeather}"
Content="Get Weather"/>
Also the command should be public and you need a text property
public Command ShowWeather { get; set; }
public string WeatherText { get; set; }
Then you need to bind the text from the viewmodel in the view.
<TextBlock Name="WeatherCondition" Margin="0,20,0,20" Text="{Binding WeatherText}"/>
also you would need to implement INotifyPropertyChanged in the viewmodel and call it when you modify the text.
WeatherText= weather.main.temp + " " + weather.name;
this.RaisePropertyChanged("WeatherText");
This pretty much basic MVVM which you can read about from here.

Related

Why is my data binding in .NET with WinUi3 not working?

MainWindow.xaml
<Window
x:Class="Prüfstand_Gallerie.MainWindow"
xmlns=http://schemas.microsoft.com/winfx/2006/xaml/presentation
xmlns:x=http://schemas.microsoft.com/winfx/2006/xaml
xmlns:local="using:Prüfstand_Gallerie"
xmlns:d=http://schemas.microsoft.com/expression/blend/2008
xmlns:mc=http://schemas.openxmlformats.org/markup-compatibility/2006 xmlns:interactivity="using:Microsoft.Xaml.Interactivity" xmlns:core="using:Microsoft.Xaml.Interactions.Core"
mc:Ignorable="d">
<StackPanel VerticalAlignment="Center" HorizontalAlignment="Center">
<TextBlock Text="{x:Bind ViewModel.FirstName}"></TextBlock>
<Button Content="Change Name" Command="{x:Bind ViewModel.ChangeNameCommand}"></Button>
</StackPanel>
</Window>
MainWindow.xaml.cs
namespace Prüfstand_Gallerie
{
public sealed partial class MainWindow : Window
{
public MainWindow()
{
this.InitializeComponent();
}
public MainWindowViewModel ViewModel { get; } = new();
}
}
MainWindowViewModel.cs
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Prüfstand_Gallerie.ViewModels
{
public partial class MainWindowViewModel : ObservableObject
{
[ObservableProperty]
public string firstName = "Jack";
[RelayCommand]
public void ChangeName()
{
FirstName = "Tjark";
}
[RelayCommand]
private void SelectItem(object param)
{
}
}
}
I'm trying to implement the mvvm pattern with winUi3, but the property FirstName is not updating when the button is clicked, though the command is fired and the value changes as I can see while debugging. It does not change in the ui. Where is the problem?
x:Bind is OneTime by default. You need to explicitly set it to OneWay.
<TextBlock Text="{x:Bind ViewModel.FirstName, Mode=OneWay}" />

The name MainViewModel does not exist in the namespace "clr-namespace:LINQ3_Test_aus_LINQ2"

I get the error message which is written in the title.
My XAML looks like this:
<Window x:Class="LINQ3_Test_aus_LINQ2.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:LINQ3_Test_aus_LINQ2"
Title="MainWindow" Height="450" Width="800">
<Window.DataContext>
<local:MainViewModel/>
</Window.DataContext>
<Grid>
<TextBox x:Name="txt_LiefNr" HorizontalAlignment="Left" Height="26" Margin="55,50,0,0" TextWrapping="Wrap" Text="{Binding LiefNr}" VerticalAlignment="Top" Width="125"/>
<TextBox x:Name="txt_LiefName" HorizontalAlignment="Left" Height="26" Margin="55,93,0,0" TextWrapping="Wrap" Text="{Binding LiefName}" VerticalAlignment="Top" Width="125"/>
<Button x:Name="btn_LiefNr" Content="Button" HorizontalAlignment="Left" Height="26" Margin="215,50,0,0" VerticalAlignment="Top" Width="116" Command="{Binding LookupCommand}"/>
</Grid>
and my MainViewModel.cs like this:
using GalaSoft.MvvmLight.Command;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Input;
namespace LINQ3_Test_aus_LINQ2
{
public class MainViewModel : INotifyPropertyChanged
{
private string _liefNr;
private string _liefName;
public ICommand LookupCommand { get; set; }
public string LiefNr
{
get { return _liefNr; }
set
{
_liefNr = value;
OnPropertyChanged();
}
}
public string LiefName
{
get { return _liefName; }
set
{
_liefName = value;
OnPropertyChanged();
}
}
public MainViewModel()
{
LookupCommand = new RelayCommand(Lookup);
}
private void Lookup()
{
Excel.OpenFile();
LiefName = Excel.Fill(LiefNr);
}
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
}
I cant find a solution to this error thats why i am asking you. I have checked multiple times if something is wrong the the names, but there is not its all written correctly.

How do I call button inside wpf data template with command

What I want is to get the CommandParameter data when I click the button in the dynamically created data source.
First I create data for item source, then I bind it with binding, then I try to capture this click event with command.
Mainwindow.xaml
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:lestplay"
mc:Ignorable="d"
Title="MainWindow" Height="450" Width="800" Loaded="Window_Loaded">
<Window.Resources>
<Style TargetType="ItemsControl" x:Key="den2">
<Setter Property="SnapsToDevicePixels" Value="true" />
<Setter Property="UseLayoutRounding" Value="True" />
<Setter Property="ItemTemplate">
<Setter.Value>
<DataTemplate>
<StackPanel>
<Button x:Name="lestplaybutton" Command="{Binding DisplayMessageCommand}" CommandParameter="{Binding Id}" Width="100" Height="50" Content="Furkan" />
</StackPanel>
</DataTemplate>
</Setter.Value>
</Setter>
</Style>
</Window.Resources>
<Grid>
<ItemsControl x:Name="le2" Style="{DynamicResource den2}">
</ItemsControl>
</Grid>
</Window>
here is the view i use to bind Icommand
MessageViewModel.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
namespace lestplay
{
public class MessageViewModel
{
public List<Person> Persons { get; set; }
public MessageCommand DisplayMessageCommand { get; set; }
public MessageViewModel()
{
DisplayMessageCommand = new MessageCommand(DisplayMessage);
}
public void DisplayMessage(string messagetext)
{
MessageBox.Show(messagetext);
}
}
}
Person.cs
The class that will hold the data I want
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace lestplay
{
public class Person
{
public string Id { get; set; }
public string Name { get; set; }
public Person(string id, string name)
{
this.Id = id;
this.Name = name;
}
}
}
MessageCommand.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Input;
namespace lestplay
{
public class MessageCommand : ICommand
{
public event EventHandler? CanExecuteChanged;
public Action<string> _execute;
public MessageCommand(Action<string> execute)
{
_execute = execute;
}
public bool CanExecute(object? parameter)
{
return true;
}
public void Execute(object? parameter)
{
_execute.Invoke(parameter as string);
}
}
}
MainWindow.xaml.cs
namespace lestplay
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void Window_Loaded(object sender, RoutedEventArgs e)
{
List<Person> prn = new List<Person>();
prn.Add(new Person() { Name = "furkan", Id = "ui-148782" });
le2.ItemsSource = prn;
DataContext = new MessageViewModel();
}
}
}

Binds not updating when messaging between view models using MVVMLight.Messaging

I'm trying to set the visibility of tab items in a viewmodel from another viewmodel.
I know the binds are correct for I can set the properties (set to false) in the constructor of the new model and they appear / disappear as I wish (setting some to true).
I know that the messenger is working for I can register to wait for a message in the constructor and send a message in the same constructor which get handled by my message callback and the binds update correctly (I can see tabs that were initially set to false).
I know this is not a race condition because I have set Console write lines and see the order in which each line is called. Create Window -> Register Message callback -> Create message and send.
Sending a message from the first ViewModel to the 2nd my callback in the new viewmodel is called and changes the properties but the view does not change (what is hidden stays hidden).
Method from original viewmodel.
private void GenerateWindowedReport()
{
Console.WriteLine("Executing View Windowed Report");
Window ReportWindow = new ReportWindow();
var msg = new TabVisibility() {
SuitesReportVisible = IncludeReportSuites,
TenantRankingsVisible = IncludeReportTenantRanking,
IndustryReportVisible = IncludeReportIndustry,
SubmarketBreakdownVisible = IncludeReportSubmarket
};
Messenger.Default.Send<TabVisibility>(msg);
ReportWindow.Show();
}
Class TabVisibility
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Analytics_Module.Messages
{
class TabVisibility
{
public bool SuitesReportVisible { get; set; }
public bool TenantRankingsVisible { get; set; }
public bool IndustryReportVisible { get; set; }
public bool SubmarketBreakdownVisible { get; set; }
}
}
New View (Is contained in the new window created in the first method)
<UserControl x:Class="Analytics_Module.Views.TabsReportView"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:local="clr-namespace:Analytics_Module.Views"
xmlns:viewModel="clr-namespace:Analytics_Module.ViewModels"
mc:Ignorable="d"
d:DesignHeight="450" d:DesignWidth="800">
<UserControl.Resources>
<BooleanToVisibilityConverter x:Key="BooleanToVisibilityConverter"/>
<viewModel:TabsReportViewModel x:Key="vmTabsReport" />
</UserControl.Resources>
<Grid DataContext="{Binding Source={StaticResource vmTabsReport}}">
<TabControl SelectedIndex="{Binding SelectedReportIndex}" >
<TabItem Header="Search Parameteres" >
<ContentControl Margin="0,10,0,5" Name="TabContentReportSearchParameters" />
</TabItem>
<TabItem Header="Suites Report"
Visibility="{Binding VisibilitySuitesReportTab,
Converter={StaticResource BooleanToVisibilityConverter}}"
IsSelected="{Binding VisibilitySuitesReportTab}">
<ContentControl Name="TabContentReportSuites" />
</TabItem>
<TabItem Header="Tenant Rankings" Visibility="{Binding VisibilityTenantRankingsTab,
Converter={StaticResource BooleanToVisibilityConverter}}">
<ContentControl Margin="0,10,0,5" Name="TabContentReportTenantRankings" />
</TabItem>
<TabItem Header="Industry Breakdown" Visibility="{Binding VisibilityIndustryBreakdownTab,
Converter={StaticResource BooleanToVisibilityConverter}}">
<ContentControl Name="TabContentReportIndustryBreakdown" />
</TabItem>
<TabItem Header="Submarket Breakdown" Visibility="{Binding VisibilitySubmarketBreakdownTab,
Converter={StaticResource BooleanToVisibilityConverter}}">
<ContentControl Name="TabContentReportSubmarketBreakdown" />
</TabItem>
</TabControl>
</Grid>
</UserControl>
Code behind of new view
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace Analytics_Module.Views
{
/// <summary>
/// Interaction logic for TabsReportView.xaml
/// </summary>
public partial class TabsReportView : UserControl
{
public TabsReportView()
{
InitializeComponent();
}
}
}
ViewModel giving me issues:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Analytics_Module.Messages;
using Analytics_Module.Utillity;
using MVVMLight.Messaging;
namespace Analytics_Module.ViewModels
{
class TabsReportViewModel : BaseViewModel
{
protected static class TabIndexConstants
{
public const int SearchParameters = 0;
public const int SuitesReport = 1;
public const int TenantRankings = 2;
public const int IndustryBreakdown = 3;
public const int SubmarketBreakdwown = 4;
}
public TabsReportViewModel() : base()
{
Console.WriteLine("TabsreportVM Constructor");
SelectedReportIndex = TabIndexConstants.SearchParameters;
VisibilitySuitesReportTab = false;
VisibilityTenantRankingsTab = false;
VisibilityIndustryBreakdownTab = false;
VisibilitySubmarketBreakdownTab = false;
Messenger.Default.Register<TabVisibility>
(this, (msgTabVisibility) => SetTabVisibility(msgTabVisibility));
Console.WriteLine("Message Registered");
TabVisibility t = new TabVisibility();
t.IndustryReportVisible = true;
t.SubmarketBreakdownVisible = true;
t.SuitesReportVisible = true;
t.TenantRankingsVisible = true;
//SetTabVisibility(t);
//Messenger.Default.Send<TabVisibility>(t);
}
public void SetTabVisibility(TabVisibility msgTabVisibility)
{
Console.WriteLine("Tabs Set Visiblity Callback");
VisibilitySuitesReportTab = (bool) msgTabVisibility.SuitesReportVisible;
VisibilityTenantRankingsTab = (bool) msgTabVisibility.TenantRankingsVisible;
VisibilityIndustryBreakdownTab = (bool) msgTabVisibility.IndustryReportVisible;
VisibilitySubmarketBreakdownTab = (bool)msgTabVisibility.SubmarketBreakdownVisible;
}
public int SelectedReportIndex { get; set; }
public bool VisibilitySuitesReportTab { get; set; }
public bool VisibilityTenantRankingsTab { get; set; }
public bool VisibilityIndustryBreakdownTab { get; set; }
public bool VisibilitySubmarketBreakdownTab { get; set; }
}
}
I found a workaround but this seems more like a hack. All I had to do was to manually trigger the OnPropertyChanged for each property.
public void SetTabVisibility(MessageTabVisibility msgTabVisibility)
{
Console.WriteLine("Tabs Set Visiblity Callback");
VisibilitySuitesReportTab = (bool) msgTabVisibility.SuitesReportVisible;
VisibilityTenantRankingsTab = (bool) msgTabVisibility.TenantRankingsVisible;
VisibilityIndustryBreakdownTab = (bool) msgTabVisibility.IndustryReportVisible;
VisibilitySubmarketBreakdownTab = (bool)msgTabVisibility.SubmarketBreakdownVisible;
Messenger.Default.Unregister<MessageTabVisibility>(this);
Console.WriteLine("Refresh");
OnPropertyChanged("VisibilitySuitesReportTab");
OnPropertyChanged("VisibilityTenantRankingsTab");
OnPropertyChanged("VisibilityIndustryBreakdownTab");
OnPropertyChanged("VisibilitySubmarketBreakdownTab");
}

Unable to use MVVM/binding correctly in the below code and having issues with Icommand property

Very new to WPF coding using MVVM. Tried making a simple calculator in WPF using MVVM. But unable to trigger the Icommand in the below code.If possible help me in this. Grateful if anybody can help me out.
View Code:
<Window x:Class="MVVMCalculator.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:MVVMCalculator"
mc:Ignorable="d"
Title="Calculator" Height="350" Width="300">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="85"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<TextBox Text="{Binding Display, Mode=OneWay}" IsReadOnly="True" TextWrapping="Wrap"
Grid.Row="0" Background="#E2E2E2" Margin="0,10,0,0" VerticalAlignment="Top"
Height="75" Width="250" HorizontalAlignment="Center" FontSize="22" FontWeight="Bold"
TextAlignment="Right">
<TextBox.Effect>
<DropShadowEffect/>
</TextBox.Effect>
</TextBox>
<ItemsControl Grid.Row="1" ItemsSource="{Binding Buttns}" Margin="15,15,15,10">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<UniformGrid Columns="5" Rows="4" />
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<ItemsControl.ItemTemplate>
<DataTemplate>
<Button Content="{Binding Txt, Mode=TwoWay}" Command="{Binding Enter_number}"
FontSize="18" FontWeight="Bold" Height="50" Width="50" Background="#eef2f3"
BorderBrush="Black" BorderThickness="1.0" Name="number">
<Button.Effect>
<DropShadowEffect/>
</Button.Effect>
</Button>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</Grid>
</Window>
ViewModel Code:
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Input;
namespace MVVMCalculator
{
class ViewModel : INotifyPropertyChanged
{
Buttons btn = new Buttons();
private decimal operand1;
private decimal operand2;
private string operation;
private decimal result;
private string display;
private bool newDisplayRequired = false;
ObservableCollection<Buttons> buttns;
public ObservableCollection<Buttons> Buttns
{
get { return buttns; }
set { buttns = value; }
}
public decimal Result
{
get { return result; }
}
public decimal Operand1
{
get { return operand1; }
set { operand1 = value; }
}
public decimal Operand2
{
get { return operand2; }
set { operand2 = value; }
}
public string Operation
{
get { return operation; }
set { operation = value; }
}
public string Display
{
get { return display; }
set { display = value;
OnPropertyChanged("Display");
}
}
public ViewModel()
{
buttns = new ObservableCollection<Buttons>
{
new Buttons("1"), new Buttons("2"), new Buttons("3"),
new Buttons("C"), new Buttons("Back"), new Buttons("4"),
new Buttons("5"), new Buttons("6"), new Buttons("CE"),
new Buttons("%"), new Buttons("7"), new Buttons("8"),
new Buttons("9"), new Buttons("/"), new Buttons("*"),
new Buttons("0"), new Buttons("."), new Buttons("+"),
new Buttons("-"), new Buttons("=")
};
display = "0";
operand1 = 0;
operand2 = 0;
operation = "";
}
public event PropertyChangedEventHandler PropertyChanged;
private void OnPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
private ICommand enter_number;
public ICommand Enter_number
{
get
{
if(enter_number==null)
{
enter_number = new DelegateCommand<string>(MyAction, _canExecute);
}
return enter_number;
}
}
private static bool _canExecute(string button)
{
return true;
}
public void MyAction(string btn)
{
switch(btn)
{
case "C":
display = "0";
operand1 = 0;
operand2 = 0;
//operation = "";
break;
case ".":
if (!display.Contains("."))
{
Display = display + ".";
}
break;
case "Back":
if (display.Length > 1)
Display = display.Substring(0, display.Length - 1);
else Display = "0";
break;
default:
if (display == "0" || newDisplayRequired)
Display = btn;
else
Display = display + btn;
break;
}
}
}
}
Buttons Class:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MVVMCalculator
{
class Buttons:INotifyPropertyChanged
{
private string txt;
public string Txt
{
get { return txt; }
set { txt = value; }
}
public Buttons(string a)
{
txt = a;
}
public Buttons()
{
}
public event PropertyChangedEventHandler PropertyChanged;
private void OnPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
}
}
Xaml.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace MVVMCalculator
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
this.DataContext = new ViewModel();
}
}
}
Since the Enter_number property is defined in the ViewModel class you need to use a {RelativeSource} to be able to bind to it:
<Button Content="{Binding Txt, Mode=TwoWay}"
Command="{Binding DataContext.Enter_number, RelativeSource={RelativeSource AncestorType=ItemsControl}}"
FontSize="18" FontWeight="Bold" Height="50" Width="50" Background="#eef2f3"
BorderBrush="Black" BorderThickness="1.0" Name="number">
<Button.Effect>
<DropShadowEffect/>
</Button.Effect>
</Button>
The default DataContext of the Button is the current Buttons object in the ItemsSource collection of the ItemsControl and that's why your binding fails.

Categories