I need to bind the text property of a textbox that it is located in a secondary window to a property that is defined in the corresponding view model of that secondary window
XAML CODE:
<Window x:Class="RG.IOManager.Views.PreferencesDialog"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:genericClasses="clr-namespace:RG.IOManager.GenericClasses"
xmlns:xctk="http://schemas.xceed.com/wpf/xaml/toolkit"
Title="Setup" Height="131" Width="332"
WindowStartupLocation="CenterOwner"
ShowInTaskbar="False"
WindowStyle="ToolWindow"
>
<Window.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="../ResourceDictionary.xaml" />
<ResourceDictionary Source="../ScrollBarTemplate.xaml" />
<ResourceDictionary Source="../Styles.xaml" />
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
</Window.Resources>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="10*" />
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<Label Content="Cycle Time" Grid.Row="0" Grid.Column="0" Height="28" HorizontalAlignment="Left" Margin="10,10,0,20" Name="label1" VerticalAlignment="Top" />
<StackPanel Grid.Row="0" Grid.Column="1" Width="190" Orientation="Horizontal">
<!--
<xctk:IntegerUpDown Name="TbMainCycleTime" Margin="10,10,0,20" Width="50" Height="25" HorizontalContentAlignment="Right"
Increment="1" Maximum="5000" Minimum="0" ShowButtonSpinner="False"/>
-->
<TextBox Name="TbMainCycleTime" Margin="10,10,0,20" Width="50" Height="25" HorizontalContentAlignment="Right" Validation.ErrorTemplate="{StaticResource ErrorTemplate}" Style="{StaticResource textBoxErrorTooltip}" >
<TextBox.Text>
<Binding Source="PreferencesDialog" Path="CycleTime" Mode="TwoWay" UpdateSourceTrigger="PropertyChanged" >
<Binding.ValidationRules>
<genericClasses:IntegersValidation Min="0" Max="1000" />
</Binding.ValidationRules>
</Binding>
</TextBox.Text>
</TextBox>
<!--<TextBox Name="TbMainCycleTime" Margin="10,10,0,20" Width="50" Height="25" HorizontalContentAlignment="Right" />-->
<Label Content="ms" Margin="1,10,10,20"/>
</StackPanel>
<StackPanel Grid.Row="1" Grid.Column="1" Width="190" Orientation="Horizontal">
<Button Content="Update" Height="23" HorizontalAlignment="Left" Margin="5,0,10,0" Name="btUpdate" VerticalAlignment="Top" Width="75" Click="btUpdate_Click" />
<Button Content="Cancel" Height="23" HorizontalAlignment="Left" Margin="5,0,10,0" Name="btCancel" VerticalAlignment="Top" Width="75" Click="btCancel_Click" />
</StackPanel>
</Grid>
CS CODE:
/// <summary>
/// Interaction logic for PreferencesDialogue.xaml
/// </summary>
public partial class PreferencesDialog : Window, INotifyPropertyChanged
{
#region Binding Properties
public event PropertyChangedEventHandler PropertyChanged;
/// <summary>
/// Main cycle time
/// </summary>
public int CycleTime
{
get { return _CycleTime; }
set
{
_CycleTime = value;
var handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs("CycleTime"));
}
}
}
private int _CycleTime;
#endregion
private IOManager _receiver;
public PreferencesDialog(IOManager receiver)
{
this._receiver = receiver;
InitializeComponent();
//this.TbMainCycleTime.Text = _receiver.globalBindingProperties.MainCycleTime.ToString();
this.CycleTime = _receiver.globalBindingProperties.MainCycleTime;
}
private void btUpdate_Click(object sender, RoutedEventArgs e)
{
_receiver.globalBindingProperties.MainCycleTime = Convert.ToInt32(this.TbMainCycleTime.Text);
this.Close();
}
private void btCancel_Click(object sender, RoutedEventArgs e)
{
this.Close();
}
}
Can someone help me to find what i did wrong? Thanks in advance
your approach is wrong. however if you change these two thing your problem will be solved:
first set DataContext of the Window:
public PreferencesDialog(IOManager receiver)
{
this.DataContext = this;
this._receiver = receiver;
InitializeComponent();
//this.TbMainCycleTime.Text = _receiver.globalBindingProperties.MainCycleTime.ToString();
this.CycleTime = _receiver.globalBindingProperties.MainCycleTime;
}
second remove 'Source' from TextBox.Text.Binding since the source is the dataContext.
<TextBox Name="TbMainCycleTime" Margin="10,10,0,20" Width="50" Height="25" HorizontalContentAlignment="Right" Validation.ErrorTemplate="{StaticResource ErrorTemplate}" Style="{StaticResource textBoxErrorTooltip}" >
<TextBox.Text>
<Binding Path="CycleTime" Mode="TwoWay" UpdateSourceTrigger="PropertyChanged" >
<Binding.ValidationRules>
<genericClasses:IntegersValidation Min="0" Max="1000" />
</Binding.ValidationRules>
</Binding>
</TextBox.Text>
</TextBox>
Have you assigned your viewmodel as datacontext to window? (class in which you have defined CycleTime)
Secondly, are you going to change cycle time for UI. You are using two way binding between TextBox and CycleTime property.
Check if this link, where I've created type safe text box extnsions. Though, article is about silverlight, you can easily use in WPF.
Change your xaml as
<Window x:Class="RG.IOManager.Views.PreferencesDialog" x:Name="PreferencesDialog"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
Related
I want to remake one kind of game from those typing games, where the words are coming from somewhere and you have to write down that word correctly.
Here is one: https://www.youtube.com/watch?v=FqNTKJRBPdc
My first problem is that I don't find nothing, how could I change dynamically the TextBox's width.
So if the whole word won't fit in the TextBox, I want to increase the TextBox's width. How could I do it?
Here is my View:
<UserControl x:Class="Prog_korny.View.GameView"
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:Prog_korny"
xmlns:vm="clr-namespace:Prog_korny.ViewModel"
mc:Ignorable="d"
d:DesignHeight="720" d:DesignWidth="1280" Name="alUO">
<UserControl.Resources>
<vm:GameViewModel x:Key="GameViewModel"/>
</UserControl.Resources>
<Grid DataContext="{Binding Source={StaticResource GameViewModel}}">
<Grid.Background>
<ImageBrush ImageSource="/Prog korny;component/Pictures/background.png"/>
</Grid.Background>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="2*" />
<ColumnDefinition Width="5*" />
<ColumnDefinition Width="3*" />
<ColumnDefinition Width="4*" />
<ColumnDefinition Width="3*" />
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="7*" />
<RowDefinition Height="1*" />
<RowDefinition Height="6*" />
<RowDefinition Height="1*" />
</Grid.RowDefinitions>
<Canvas Grid.ColumnSpan="5" Grid.RowSpan="4"></Canvas>
<TextBox x:Name="txtText" Grid.Column="2" Grid.Row="1" Grid.ColumnSpan="1" Background="Transparent" Foreground="White" BorderBrush="Blue" FontFamily="Bebas Neue" FontSize="35" TextAlignment="Center" VerticalAlignment="Center" Cursor="Hand">
<TextBox.Text>
<Binding Path="textContent" UpdateSourceTrigger="PropertyChanged"/>
</TextBox.Text>
</TextBox>
<Label x:Name="lblLevel" Grid.Column="0" Grid.Row="4" Grid.ColumnSpan="1" Foreground="White" BorderBrush="{x:Null}" FontFamily="Bebas Neue" FontSize="30" Cursor="Hand">
<Label.Content>
<Binding Path="LevelLabel" UpdateSourceTrigger="PropertyChanged"/>
</Label.Content>
</Label>
<Label x:Name="lblScore" Grid.Column="4" Grid.Row="4" Grid.ColumnSpan="1" Foreground="White" BorderBrush="{x:Null}" FontFamily="Bebas Neue" FontSize="30" Cursor="Hand">
<Label.Content>
<Binding Path="ScoreLabel" UpdateSourceTrigger="PropertyChanged"/>
</Label.Content>
</Label>
</Grid>
</UserControl>
ViewModel:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Prog_korny.ViewModel
{
class GameViewModel : ViewModelBase
{
private string _textContent;
public string TextContent
{
get { return _textContent; }
set { _textContent = value; }
}
private string _levelLabel = "Level: 0";
public string LevelLabel
{
get { return _levelLabel; }
set { _levelLabel = value; }
}
private string _scoreLabel = "Score: 0";
public string ScoreLabel
{
get { return _scoreLabel; }
set { _scoreLabel = value; }
}
}
}
you can define a property which you will bind with the width property in xaml page.
You can control the property from viewmodel based on your given condition.
You can control almost everything which is available to you in your window xaml page.Plus you can define conditional logic based on pairing of two properties.
like if your TextContent property reaches certain limit then set text width property to something.
With low level of control you can achieve controlling width via data triggers.
<Style>
<Setter Property="Width" Value="200"/>
<Style.Triggers>
<<Put your conditions which will set the value>>
</Style.Triggers>
</Style>
I am looking for a way to change the header on a re-used user control from the containing XAML.
User Control:
<UserControl x:Class="ReusableControl"
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"
mc:Ignorable="d"
d:DesignHeight="150" d:DesignWidth="300">
<Grid>
<GroupBox Header="Config Number">
<Grid Name="MyConfig">
<Grid.RowDefinitions>
<RowDefinition Height="60" />
<RowDefinition Height="60" />
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="80" />
<ColumnDefinition Width="*" MinWidth="100"/>
</Grid.ColumnDefinitions>
<Label Name="Value1Label" Grid.Row="0" Grid.Column="0" VerticalAlignment="Center" HorizontalAlignment="Left">Value 1</Label>
<TextBox Grid.Row="0" Grid.Column="1"
HorizontalContentAlignment="Left" VerticalContentAlignment="Center"
IsEnabled="True" Margin="5,5,5,5">
<TextBox.Text>
<Binding Path="Value1" StringFormat="{}{0:0.0#######}" Mode="TwoWay" UpdateSourceTrigger="PropertyChanged" ValidatesOnDataErrors="True" />
</TextBox.Text>
</TextBox>
<Label Name="Value2Label" Grid.Row="1" Grid.Column="0" VerticalAlignment="Center" HorizontalAlignment="Left">Value 2</Label>
<TextBox Grid.Row="1" Grid.Column="1"
HorizontalContentAlignment="Left" VerticalContentAlignment="Center"
IsEnabled="True" Margin="5,5,5,5">
<TextBox.Text>
<Binding Path="Value2" StringFormat="{}{0:0.0#######}" Mode="TwoWay" UpdateSourceTrigger="PropertyChanged" ValidatesOnDataErrors="True" />
</TextBox.Text>
</TextBox>
</Grid>
</GroupBox>
</Grid>
Containing Window:
<Window x:Class="MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:StackExchangeQuestion"
Title="MainWindow" Height="500" Width="525">
<Grid>
<StackPanel Orientation="Vertical">
<local:ReusableControl x:Name="Config1" />
<local:ReusableControl x:Name="Config2" />
<local:ReusableControl x:Name="Config3" />
</StackPanel>
</Grid>
The intent being so that the successive controls say "Config 1", "Config 2", Config 3", rather than "Config Number" three times.
Thanks in advance for the help!
In your ReusableControl.xaml.cs define a DependencyProperty like this:
public string Header
{
get { return (string)GetValue(HeaderProperty); }
set { SetValue(HeaderProperty, value); }
}
public static readonly DependencyProperty HeaderProperty =
DependencyProperty.Register("Header",
typeof(string), typeof(ReusableControl));
Now you can use this Header property as source of a Binding for the Header property of the internal GroupBox:
<GroupBox Header="{Binding Header,
RelativeSource={RelativeSource AncestorType=local:ReusableControl}}">
Now you will see that this:
<StackPanel Orientation="Vertical">
<local:ReusableControl x:Name="Config1" Header="Config 1"/>
<local:ReusableControl x:Name="Config2" Header="Config 2"/>
<local:ReusableControl x:Name="Config3" Header="Config 3"/>
</StackPanel>
does anyone knows if there is any issue binding data using windows 10 and visual studio 10 WPF project?
it should be very simple code line and i don't see any reason why the data is not binding
the data is biding in the xaml so i dont see other problem
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Windows;
using WpfApplication2.ViewModel;
namespace WpfApplication2
{
/// <summary>
/// Interaction logic for App.xaml
/// </summary>
public partial class App : Application
{
protected override void OnStartup(StartupEventArgs e)
{
WpfApplication2.MainWindow window = new MainWindow();
UserViewModel VM = new UserViewModel();
window.DataContext = VM;
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Input;
namespace WpfApplication2.ViewModel
{
class UserViewModel
{
private IList<User> _UsersList;
public UserViewModel()
{
_UsersList = new List<User>
{
new User{UserId = 1,FirstName="Raj",LastName="Beniwal",City="Delhi",State="DEL",Country="INDIA"},
new User{UserId=2,FirstName="Mark",LastName="henry",City="New York", State="NY", Country="USA"},
new User{UserId=3,FirstName="Mahesh",LastName="Chand",City="Philadelphia", State="PHL", Country="USA"},
new User{UserId=4,FirstName="Vikash",LastName="Nanda",City="Noida", State="UP", Country="INDIA"},
new User{UserId=5,FirstName="Harsh",LastName="Kumar",City="Ghaziabad", State="UP", Country="INDIA"},
new User{UserId=6,FirstName="Reetesh",LastName="Tomar",City="Mumbai", State="MP", Country="INDIA"},
new User{UserId=7,FirstName="Deven",LastName="Verma",City="Palwal", State="HP", Country="INDIA"},
new User{UserId=8,FirstName="Ravi",LastName="Taneja",City="Delhi", State="DEL", Country="INDIA"}
};
}
public IList<User> Users
{
get { return _UsersList; }
set { _UsersList = value; }
}
private ICommand mUpdater;
public ICommand UpdateCommand
{
get
{
if (mUpdater == null)
mUpdater = new Updater();
return mUpdater;
}
set
{
mUpdater = value;
}
}
private class Updater : ICommand
{
#region ICommand Members
public bool CanExecute(object parameter)
{
return true;
}
public event EventHandler CanExecuteChanged;
public void Execute(object parameter)
{
}
#endregion
}
}
}
<Window x:Class="WpfApplication2.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="485" Width="525">
<Grid Margin="0,0,0,20">
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="*"/>
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
<ListView Name="UserGrid" Grid.Row="1" Margin="4,178,12,13" ItemsSource="{Binding Users}" >
<ListView.View>
<GridView x:Name="grdTest">
<GridViewColumn Header="UserId" DisplayMemberBinding="{Binding UserId}" Width="50"/>
<GridViewColumn Header="First Name" DisplayMemberBinding="{Binding FirstName}" Width="80" />
<GridViewColumn Header="Last Name" DisplayMemberBinding="{Binding LastName}" Width="100" />
<GridViewColumn Header="City" DisplayMemberBinding="{Binding City}" Width="80" />
<GridViewColumn Header="State" DisplayMemberBinding="{Binding State}" Width="80" />
<GridViewColumn Header="Country" DisplayMemberBinding="{Binding Country}" Width="100" />
</GridView>
</ListView.View>
</ListView>
<TextBox Grid.Row="1" Height="23" HorizontalAlignment="Left" Margin="80,7,0,0" Name="txtUserId" VerticalAlignment="Top" Width="178" Text="{Binding ElementName=UserGrid,Path=SelectedItem.UserId}" />
<TextBox Grid.Row="1" Height="23" HorizontalAlignment="Left" Margin="80,35,0,0" Name="txtFirstName" VerticalAlignment="Top" Width="178" Text="{Binding ElementName=UserGrid,Path=SelectedItem.FirstName}" />
<TextBox Grid.Row="1" Height="23" HorizontalAlignment="Left" Margin="80,62,0,0" Name="txtLastName" VerticalAlignment="Top" Width="178" Text="{Binding ElementName=UserGrid,Path=SelectedItem.LastName}" />
<Label Content="UserId" Grid.Row="1" HorizontalAlignment="Left" Margin="12,12,0,274" Name="label1" />
<Label Content="Last Name" Grid.Row="1" Height="28" HorizontalAlignment="Left" Margin="12,60,0,0" Name="label2" VerticalAlignment="Top" />
<Label Content="First Name" Grid.Row="1" Height="28" HorizontalAlignment="Left" Margin="12,35,0,0" Name="label3" VerticalAlignment="Top" />
<Button Content="Update" Grid.Row="1" Height="23" HorizontalAlignment="Left" Margin="310,40,0,0" Name="btnUpdate"
VerticalAlignment="Top" Width="141"
Command="{Binding Path=UpdateCommad}" />
<TextBox Grid.Row="1" Height="23" HorizontalAlignment="Left" Margin="80,143,0,0" x:Name="txtCity" VerticalAlignment="Top" Width="178" Text="{Binding SelectedItem.City, ElementName=UserGrid}" />
<Label Content="Country" Grid.Row="1" Height="28" HorizontalAlignment="Left" Margin="12,141,0,0" x:Name="label2_Copy" VerticalAlignment="Top" />
<TextBox Grid.Row="1" Height="23" HorizontalAlignment="Left" Margin="80,88,0,0" x:Name="txtCountry" VerticalAlignment="Top" Width="178" Text="{Binding SelectedItem.Country, ElementName=UserGrid}" />
<Label Content="City" Grid.Row="1" Height="28" HorizontalAlignment="Left" Margin="12,86,0,0" x:Name="label2_Copy1" VerticalAlignment="Top" />
<TextBox Grid.Row="1" Height="23" HorizontalAlignment="Left" Margin="80,115,0,0" x:Name="txtSTate" VerticalAlignment="Top" Width="178" Text="{Binding SelectedItem.State, ElementName=UserGrid}" />
<Label Content="State" Grid.Row="1" Height="28" HorizontalAlignment="Left" Margin="12,113,0,0" x:Name="label2_Copy2" VerticalAlignment="Top" />
</Grid>
</Window>
Use ObservableCollection instead of List:
private ObservableCollection<User> _users = new ObservableCollection<User>();
public ObservableCollection<User> Users
{
get { return _users; }
set
{
_users= value;
OnPropertyChanged();
}
}
As you are using 'IList' the problem is that the list initially is empty when binded to UI. The bindings take place when InitializeComponent() is called. Hence the ItemsSource property has to be updated.
UserGrid.ItemsSource = Users;
Adding the above line will solve your problem.
It is better to use ObservableCollection instead of List, as it automatically updates the UI when any change has been made on the binded value.
I used PasswordHelper class to bind passwordbox with viewmodel but still property field is null at submit time. i tried with debugger but property doesn't getting value.
XAML Code..
<Page x:Class="ChatApp.View.Register"
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:i="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity"
xmlns:se="http://schemas.microsoft.com/expression/2010/interactions"
xmlns:vm="clr-namespace:ChatApp.ViewModel"
xmlns:w="clr-namespace:ChatApp"
mc:Ignorable="d"
d:DesignHeight="347" d:DesignWidth="350"
Title="Register">
<Page.DataContext>
<vm:RegisterViewModel></vm:RegisterViewModel>
</Page.DataContext>
<Grid Height="317">
<Grid.RowDefinitions>
<RowDefinition Height="30" />
<RowDefinition Height="30" />
<RowDefinition Height="30" />
<RowDefinition Height="30" />
<RowDefinition Height="30" />
<RowDefinition Height="30" />
<RowDefinition Height="63" />
<RowDefinition Height="32" />
<RowDefinition Height="42*" />
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="112*"/>
<ColumnDefinition Width="188*" />
</Grid.ColumnDefinitions>
<Label Content="User ID :" Grid.Row="1" Height="28" HorizontalAlignment="Left" Margin="12,0,0,0" Name="label1" VerticalAlignment="Top" />
<Label Content="Password :" Grid.Row="2" Height="28" HorizontalAlignment="Left" Margin="12,2,0,0" Name="label2" VerticalAlignment="Top" />
<Label Content="Name" Grid.Row="3" Height="28" HorizontalAlignment="Left" Margin="12,0,0,0" Name="label3" VerticalAlignment="Top" />
<Label Content="Email ID :" Grid.Row="4" Height="28" HorizontalAlignment="Left" Margin="12,2,0,0" Name="label4" VerticalAlignment="Top" />
<Label Content="Contact No :" Grid.Row="5" Height="29" HorizontalAlignment="Left" Margin="12,1,0,0" Name="label5" VerticalAlignment="Top" />
<Label Content="Address :" Grid.Row="6" Height="28" HorizontalAlignment="Left" Margin="12,0,0,0" Name="label6" VerticalAlignment="Top" />
<Label Content="Designation :" Grid.Row="7" Height="28" HorizontalAlignment="Left" Margin="12,0,0,0" Name="label7" VerticalAlignment="Top" />
<TextBox Text="{Binding userID}" Grid.Column="1" Grid.Row="1" Height="23" HorizontalAlignment="Left" Margin="0,3,0,0" Name="txtID" VerticalAlignment="Top" Width="207" />
<TextBox Grid.Column="1" Text="{Binding password}" Grid.Row="2" Height="23" HorizontalAlignment="Left" Name="txtpassword" VerticalAlignment="Top" Width="207" Margin="0,2,0,0" />
<TextBox Text="{Binding name}" Grid.Column="1" Grid.Row="3" Height="23" HorizontalAlignment="Left" Name="txtName" VerticalAlignment="Top" Width="207" Margin="0,2,0,0" />
<TextBox Text="{Binding emailID}" Grid.Column="1" Grid.Row="4" Height="23" HorizontalAlignment="Left" Margin="0,2,12,0" Name="txtEmail" VerticalAlignment="Top" Width="207" />
<TextBox Text="{Binding contact}" Grid.Column="1" Grid.Row="5" Height="23" HorizontalAlignment="Left" Name="txtContact" VerticalAlignment="Top" Width="207" Margin="0,2,0,0" />
<TextBox Text="{Binding address}" Grid.Column="1" Grid.Row="6" Height="56" HorizontalAlignment="Left" Margin="0,2,0,0" Name="txtAddress" VerticalAlignment="Top" Width="207" TextWrapping="Wrap" HorizontalScrollBarVisibility="Auto" VerticalScrollBarVisibility="Auto" />
<TextBox Text="{Binding designation}" Grid.Column="1" Grid.Row="7" Height="23" HorizontalAlignment="Left" Name="txtDesignation" VerticalAlignment="Top" Width="207" Margin="0,1,0,0" />
<TextBlock Height="28" HorizontalAlignment="Left" Margin="49,1,0,0" Name="textBlock1" Text="New Registration" VerticalAlignment="Top" Width="169" Grid.ColumnSpan="2" FontWeight="Bold" FontSize="20" />
<Button Content="Register" Grid.Row="8" Height="23" HorizontalAlignment="Left" Margin="33,5,0,0" Name="btnSubmit" VerticalAlignment="Top" Width="75" Grid.Column="1">
<i:Interaction.Triggers>
<i:EventTrigger SourceObject="{Binding ElementName=btnSubmit}" EventName="Click">
<se:CallMethodAction MethodName="SubmitDetail" TargetObject="{Binding DataContext, ElementName=btnSubmit}" />
</i:EventTrigger>
</i:Interaction.Triggers>
</Button>
</Grid>
here is my password helper class.
public static class PasswordHelper
{
public static readonly DependencyProperty PasswordProperty =
DependencyProperty.RegisterAttached("Password",
typeof(string), typeof(PasswordHelper),
new FrameworkPropertyMetadata(string.Empty, OnPasswordPropertyChanged));
public static readonly DependencyProperty AttachProperty =
DependencyProperty.RegisterAttached("Attach",
typeof(bool), typeof(PasswordHelper), new PropertyMetadata(false, Attach));
private static readonly DependencyProperty IsUpdatingProperty =
DependencyProperty.RegisterAttached("IsUpdating", typeof(bool),
typeof(PasswordHelper));
public static void SetAttach(DependencyObject dp, bool value)
{
dp.SetValue(AttachProperty, value);
}
public static bool GetAttach(DependencyObject dp)
{
return (bool)dp.GetValue(AttachProperty);
}
public static string GetPassword(DependencyObject dp)
{
return (string)dp.GetValue(PasswordProperty);
}
public static void SetPassword(DependencyObject dp, string value)
{
dp.SetValue(PasswordProperty, value);
}
private static bool GetIsUpdating(DependencyObject dp)
{
return (bool)dp.GetValue(IsUpdatingProperty);
}
private static void SetIsUpdating(DependencyObject dp, bool value)
{
dp.SetValue(IsUpdatingProperty, value);
}
private static void OnPasswordPropertyChanged(DependencyObject sender,
DependencyPropertyChangedEventArgs e)
{
PasswordBox passwordBox = sender as PasswordBox;
passwordBox.PasswordChanged -= PasswordChanged;
if (!(bool)GetIsUpdating(passwordBox))
{
passwordBox.Password = (string)e.NewValue;
}
passwordBox.PasswordChanged += PasswordChanged;
}
private static void Attach(DependencyObject sender, DependencyPropertyChangedEventArgs e)
{
PasswordBox passwordBox = sender as PasswordBox;
if (passwordBox == null)
return;
if ((bool)e.OldValue)
{
passwordBox.PasswordChanged -= PasswordChanged;
}
if ((bool)e.NewValue)
{
passwordBox.PasswordChanged += PasswordChanged;
}
}
private static void PasswordChanged(object sender, RoutedEventArgs e)
{
PasswordBox passwordBox = sender as PasswordBox;
SetIsUpdating(passwordBox, true);
SetPassword(passwordBox, passwordBox.Password);
SetIsUpdating(passwordBox, false);
}
}
I see two problems with your code:
1.
XAML is case sensitive with regards to binding paths, but you have used lower cased property names in your XAML. (You can find out more from the 'Case and Whitespace in XAML' section of the XAML Overview (WPF) page at MSDN.
XAML is generally speaking case sensitive. For purposes of resolving backing types, WPF XAML is case sensitive by the same rules that the CLR is case sensitive. Object elements, property elements, and attribute names must all be specified by using the sensitive casing when compared by name to the underlying type in the assembly, or to a member of a type.
2.
You do not need to set the Password property of the PasswordBox in your OnPasswordPropertyChanged handler, although this shouldn't cause your described problem.
I'm getting an unhandled exception when loading the designer (VS2010)
These are the details.
System.NullReferenceException
Object reference not set to an instance of an object.
at MahApps.Metro.Controls.TextboxHelper.TextBoxLoaded(Object sender, RoutedEventArgs e)
at System.Windows.RoutedEventHandlerInfo.InvokeHandler(Object target, RoutedEventArgs routedEventArgs)
at System.Windows.EventRoute.InvokeHandlersImpl(Object source, RoutedEventArgs args, Boolean reRaised)
at System.Windows.UIElement.RaiseEventImpl(DependencyObject sender, RoutedEventArgs args)
at System.Windows.UIElement.RaiseEvent(RoutedEventArgs e)
at System.Windows.BroadcastEventHelper.BroadcastEvent(DependencyObject root, RoutedEvent routedEvent)
at System.Windows.BroadcastEventHelper.BroadcastLoadedEvent(Object root)
at MS.Internal.LoadedOrUnloadedOperation.DoWork()
at System.Windows.Media.MediaContext.FireLoadedPendingCallbacks()
at System.Windows.Media.MediaContext.FireInvokeOnRenderCallbacks()
at System.Windows.Media.MediaContext.RenderMessageHandlerCore(Object resizedCompositionTarget)
at System.Windows.Media.MediaContext.RenderMessageHandler(Object resizedCompositionTarget)
at System.Windows.Threading.ExceptionWrapper.InternalRealCall(Delegate callback, Object args, Int32 numArgs)
at MS.Internal.Threading.ExceptionFilterHelper.TryCatchWhen(Object source, Delegate method, Object args, Int32 numArgs, Delegate catchHandler)
I have tried
--commenting out all text boxes
--commenting out all code in my viewmodel constructor
--commenting out the MainWindowVieWModel creation in the MainWindow constructor...
I'm baffled..
Code...
public partial class MainWindow : MetroWindow
{
public MainWindowViewModel ViewModel { get; protected set; }
public MainWindow()
{
ViewModel = new MainWindowViewModel(new AppModel());
InitializeComponent();
}
public class AppModel : ReactiveValidatedObject
{
public ReactiveCollection<SheetModel> CompletedSheets { get; protected set; }
public void RefreshData()
{
List<SheetModel> sheets = DataLayer.LoadData();
CompletedSheets = new ReactiveCollection<SheetModel>();
foreach (var sheetModel in sheets)
{
CompletedSheets.Add(sheetModel);
}
}
public AppModel()
{
CompletedSheets = new ReactiveCollection<SheetModel>();
}
Constructor for main window view model is empty, so shouldn't be any issues there.
MainWindowXaml...
<Controls:MetroWindow
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:Controls="clr-namespace:MahApps.Metro.Controls;assembly=MahApps.Metro"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
x:Class="TimeSheet.MainWindow"
Title="MainWindow"
x:Name="Window"
Height="270"
MinWidth="490"
Width="600"
xmlns:local="clr-namespace:TimeSheet"
ShowTitleBar="False" WindowStartupLocation="CenterScreen"
DataContext="{Binding ViewModel, ElementName=Window}">
<Controls:MetroWindow.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="pack://application:,,,/MahApps.Metro;component/Styles/Colours.xaml" />
<ResourceDictionary Source="pack://application:,,,/MahApps.Metro;component/Styles/Fonts.xaml" />
<ResourceDictionary Source="pack://application:,,,/MahApps.Metro;component/Styles/Controls.xaml" />
<ResourceDictionary Source="pack://application:,,,/MahApps.Metro;component/Styles/Accents/Blue.xaml" />
<ResourceDictionary Source="pack://application:,,,/MahApps.Metro;component/Styles/Accents/BaseLight.xaml" />
</ResourceDictionary.MergedDictionaries>
<DataTemplate x:Key="CompletedBlockTile">
<StackPanel Orientation="Vertical" Margin="10,0,0,0">
<TextBlock Text="{Binding Date}" FontWeight="Bold" FontFamily="Segoe UI" />
</StackPanel>
</DataTemplate>
<DataTemplate x:Key="TaskTemplate">
<Grid HorizontalAlignment="Stretch">
<Grid.ColumnDefinitions>
<ColumnDefinition MinWidth="80px"/>
<ColumnDefinition Width="50px" />
<ColumnDefinition Width="40px"/>
<ColumnDefinition Width="40px"/>
</Grid.ColumnDefinitions>
<TextBlock Grid.Column="0" Text="{Binding Description}" Height="25.3" Margin="0" HorizontalAlignment="Stretch"/>
<TextBlock Grid.Column="1" Text="{Binding Duration}" Margin="0,0,0,0" Height="25.3" Width="45.625"/>
<Button Grid.Column="2" Content=">>" HorizontalAlignment="Right" Width="38" Command="{Binding ReStartCommand}"/>
<Button Grid.Column="3" Content="STOP" VerticalAlignment="Top" Margin="0,0,0,0" Command="{Binding StopCommand}" HorizontalAlignment="Right" Width="35"/>
</Grid>
</DataTemplate>
<BitmapImage x:Key="SearchImage" UriSource="Images/blue-37.png" />
</ResourceDictionary>
</Controls:MetroWindow.Resources>
<Controls:MetroWindow.WindowCommands>
<Controls:WindowCommands>
<Button x:Name="thisButton">
<StackPanel Orientation="Horizontal">
<StackPanel Orientation="Horizontal">
<Label Margin="0,0,55,0" Content="09:00"/>
<Label Margin="0,0,5,0" Content="Friday 20th July 2012"/>
<TextBox Controls:TextboxHelper.Watermark="search"
Controls:TextboxHelper.ClearTextButton="True"
VerticalAlignment="Top"
HorizontalAlignment="Left"
Width="154.002" />
<Button Style="{DynamicResource ChromelessButtonStyle}" Click="Button_Click">
<Image Source="{StaticResource SearchImage}" Width="20"/>
</Button>
</StackPanel>
</StackPanel>
</Button>
</Controls:WindowCommands>
</Controls:MetroWindow.WindowCommands>
<DockPanel Margin="0,0,0,0" >
<DockPanel DockPanel.Dock="Left" Margin="0,0,0,0" Width="176.625" >
<ListBox Background="Transparent"
BorderBrush="Transparent"
Margin="0,30,0,0"
ItemsSource="{Binding CompletedSheets}"
ItemTemplate="{DynamicResource CompletedBlockTile}"
SelectedItem="{Binding SelectedTimeSheet}"/>
</DockPanel>
<DockPanel DockPanel.Dock="Right" >
<Grid Margin="0,30,0,0" VerticalAlignment="Top" DockPanel.Dock="Top">
<Grid Margin="0,0,14,0.805">
<local:TextBoxChangeExt
MinWidth="200"
Controls:TextboxHelper.Watermark="Task Name"
Controls:TextboxHelper.ClearTextButton="True"
d:LayoutOverrides="Height"
Margin="8,0,70,0"
Background="{x:Null}"
Text="{Binding NewTaskName}">
</local:TextBoxChangeExt>
<Button HorizontalAlignment="Right"
Width="57"
d:LayoutOverrides="HorizontalAlignment, Height"
Content="Start"
Command="{Binding StartCommand}" IsEnabled="{Binding StartNewEnabled}"/>
</Grid>
</Grid>
<Grid DockPanel.Dock="Bottom">
<ListBox Margin="8,8,5,5"
BorderBrush="{x:Null}"
ItemTemplate="{DynamicResource TaskTemplate}"
ItemsSource="{Binding SelectedTimeSheet.Tasks}"
HorizontalContentAlignment="Stretch"
/>
</Grid>
</DockPanel>
</DockPanel>
I'm pretty sure this is a bug. I'm getting the same error, and when following the stack-trace to the line in my ViewModel, I see that I'm appropriately checking for null. Everything seems to work during run-time, but I think this is a bug when using implimentations of iCommand in designer.
Let us know if you found your cause to be different.
I'm also using VS 2010.