Edit Text MotionEventActions when 'IsEnabled=False' - xaml

I have that show/hide pass feature and it works just fine. One of my views ilustrated below has a security code that effect is also applied on Entry Text that has property 'IsEnabled=False'. Right now when I click on an eye nothing happens.
Is there any way to get it working when text entry is not enabled?
<StackLayout Grid.Row="1" IsVisible="{Binding IsPINSectionVisible}">
<Label
Style="{StaticResource MessageLabelStyle}"
Text="{i18n:Translate Pin_Text}">
</Label>
</StackLayout>
<StackLayout Grid.Row="2" IsVisible="{Binding IsPINSectionVisible}">
<Entry Text="{Binding PIN.Value, Mode=TwoWay}"
IsEnabled="False"
IsPassword="True"
Placeholder="{i18n:Translate Pin_Title}">
<Entry.Style>
<OnPlatform x:TypeArguments="Style"
Android="{StaticResource EntryStyle}" />
</Entry.Style>
<Entry.Behaviors>
<behaviors:EventToCommandBehavior
EventName="TextChanged"
Command="{Binding ValidatePINCommand}" />
</Entry.Behaviors>
<Entry.Effects>
<effects:ShowHidePassEffect />
</Entry.Effects>
<Entry.Triggers>
<DataTrigger
TargetType="Entry"
Binding="{Binding PIN.IsValid}"
Value="False">
<Setter Property="behaviors:LineColorBehavior.LineColor"
Value="{StaticResource ErrorColor}" />
<Setter Property="Entry.PlaceholderColor"
Value="{StaticResource ErrorColor}" />
</DataTrigger>
</Entry.Triggers>
</Entry>
And Android Effect class:
public class ShowHidePassEffect : PlatformEffect
{
protected override void OnAttached()
{
ConfigureControl();
}
protected override void OnDetached()
{
}
private void ConfigureControl()
{
EditText editText = ((EditText)Control);
editText.SetCompoundDrawablesRelativeWithIntrinsicBounds(0, 0, Resource.Drawable.pass_show_24, 0);
editText.SetOnTouchListener(new OnDrawableTouchListener());
}
}
public class OnDrawableTouchListener : Java.Lang.Object, Android.Views.View.IOnTouchListener
{
public bool OnTouch(Android.Views.View v, MotionEvent e)
{
if (v is EditText && e.Action == MotionEventActions.Up)
{
EditText editText = (EditText)v;
if (e.RawX >= (editText.Right - editText.GetCompoundDrawables()[2].Bounds.Width()))
{
if (editText.TransformationMethod == null)
{
editText.TransformationMethod = PasswordTransformationMethod.Instance;
editText.SetCompoundDrawablesRelativeWithIntrinsicBounds(0, 0, Resource.Drawable.pass_show_24, 0);
}
else
{
editText.TransformationMethod = null;
editText.SetCompoundDrawablesRelativeWithIntrinsicBounds(0, 0, Resource.Drawable.pass_hide_24, 0);
}
return true;
}
}
return false;
}
}
And picture to ilustrate the view:

Related

Two ways Binding between a Slider and Entry

I would like to bind an Entry with a Slider and vice versa. I wrote something like this:
<Entry x:Name="myEntry" Text="{Binding Value, Mode=TwoWay}" BindingContext="{x:Reference slider}"/>
<Slider x:Name="slider" Maximum="100" Minimum="0" BindingContext="{x:Reference myEntry}"/>
When I use the slider, the value in the entry is updated, but when I put manually some value in the Entry, the value append a 0 or change to 0. What can be the problem. I am working on android.
You should bind both your Slider and Entry to string/ integer in a backing View Model.
class MyViewModel
{
private int _sliderValue;
public string EntryText
{
get => _sliderValue.ToString();
set => SetProperty(ref _sliderValue, int.Parse(value) );
}
public int SliderValue
{
get => _sliderValue;
set => (ref _sliderValue, value);
}
}
And in the view
<Entry Text="{Binding EntryText}" />
<Slider Value="{Binding SliderValue}" />
More MVVM Info
Fresh MVVM for Xamarin
Caliburn Micro for Xamarin
please refer the following xaml code
<Frame HorizontalOptions="FillAndExpand" VerticalOptions="StartAndExpand">
<StackLayout>
<Entry Text="{Binding Path=Value}"
FontSize="18"
x:Name="label"
BindingContext="{x:Reference Name=slider}"/>
<Slider x:Name="slider"
Maximum="1500"
VerticalOptions="CenterAndExpand" />
</StackLayout>
</Frame>
The same can be achieved by using the view model please refer the code
Xaml
<Frame HorizontalOptions="FillAndExpand" VerticalOptions="StartAndExpand">
<StackLayout>
<Entry x:Name="NameEntry" Placeholder="Enter Name" Text="{Binding Forename,Mode=TwoWay}" />
<Slider Value="{Binding Forename}" Minimum="0" Maximum="10"/>
</StackLayout>
</Frame>
------------------- now see the model in a c# file-----------------------------------
public partial class MainPage : ContentPage
{
public class DetailsViewModel : INotifyPropertyChanged
{
int forename;
public int Forename
{
get
{
return forename;
}
set
{
if (forename != value)
{
forename = value;
OnPropertyChanged ("Forename");
}
}
}
protected virtual void OnPropertyChanged(string propertyName)
{
var changed = PropertyChanged;
if (changed != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
public event PropertyChangedEventHandler PropertyChanged;
}
public MainPage()
{
InitializeComponent();
BindingContext = new DetailsViewModel();
}
}

MVVM binding cutom property to view model

I am new in MVVVM so please forgive me if it is stupid question. I am using this example http://www.codeproject.com/Articles/36848/WPF-Image-Pixel-Color-Picker-Element and included there library to get color of indicated by user pixel of image. it looks nice and dipsalys in rectangle selected color but i neeed to bind the selecteed value to viewmodel.
here is my xaml code:
<Window x:Class="MovieEditor.View.PixelSelector"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:ctrls="clr-namespace:ColorPickerControls;assembly=ColorPickerControls"
xmlns:local="clr-namespace:MovieEditor.MVVMCommon"
Title="FilterDesigner" Height="550" Width="550"
Icon="..\Resources\Images\icon.ico"
xmlns:VM="clr-namespace:MovieEditor.ViewModel">
<Window.DataContext>
<VM:PixelSelectorVM/>
</Window.DataContext>
<Window.Resources>
<local:ColorToBrushConverter x:Key="ColorToBrushConverter"/>
</Window.Resources>
<Grid Background="#FF191919" >
<DockPanel>
<Grid Margin="10,10,10,1">
<Grid.RowDefinitions>
<RowDefinition/>
<RowDefinition Height="Auto" MinHeight="38"/>
</Grid.RowDefinitions>
<Border BorderBrush="White" BorderThickness="5" Margin="0,39,0,11">
<ctrls:ImageColorPicker Binding.XmlNamespaceManager="{Binding p PixelSelectorVM.MyImageColorPicker, UpdateSourceTrigger=PropertyChanged}"
x:Name="image" Source ="{Binding Frame}" Margin="0,36,0,0"
/>
</Border>
<Border Width="77"
HorizontalAlignment="Center"
BorderBrush="White" BorderThickness="1" Margin="263,2,182,435">
<Rectangle Fill="{Binding ElementName=image, Path=SelectedColor,
Converter={StaticResource ColorToBrushConverter}}" RenderTransformOrigin="0.549,0.429" Margin="1"/>
</Border>
<Button Content="Save" Command="{Binding Save}" Margin="165,0,0,4" Grid.Row="1" HorizontalAlignment="Left" Width="60"/>
<Label Content="Selected pixel color:" HorizontalAlignment="Left" Height="18" Margin="140,11,0,0" VerticalAlignment="Top" Width="110"/>
<Button Content="Cancel" Command="{Binding Cancel}" Margin="0,1,165,4" HorizontalAlignment="Right" Width="60" RenderTransformOrigin="0.5,0.5" Grid.Row="1">
</Button>
</Grid>
</DockPanel>
</Grid>
</Window>
</code>
And here is my view model:
public class PixelSelectorVM : ViewModelBase
{
private BitmapImage frame;
public MainWindowVM parentMainWindowVM;
private ImageColorPicker imageColorPicker;
public ImageColorPicker MyImageColorPicker
{
get
{
return this.imageColorPicker;
}
set
{
this.imageColorPicker = value;
OnPropertyChanged("MyImageColorPicker");
}
}
public BitmapImage Frame
{
get
{
return this.frame;
}
set
{
this.frame = value;
OnPropertyChanged("Frame");
}
}
public PixelSelectorVM(BitmapImage image, MainWindowVM mainWindowVM)
{
this.frame = image;
this.parentMainWindowVM = mainWindowVM;
this.imageColorPicker = new ImageColorPicker();
this.imageColorPicker.Source = image;
}
public PixelSelectorVM() { }
public ICommand Save
{
get
{
return new RelayCommand(SaveExecute);
}
}
public ICommand Cancel
{
get
{
return new RelayCommand(CancelExecute);
}
}
private void SaveExecute()
{
}
private void CancelExecute()
{
}
}
Please suggest me solution how can i pass the selected color to view model
You should be able to bind ImageColorPicker's SelectedColor to ViewModel's Property.
So in XAML add the binding:
SelectedColor="{Binding MySelectedColor, Mode=TwoWay}"
And in VM add the MySelectedColor property:
private Color selectedColor;
public Color MySelectedColor
{
get
{
return this.selectedColor;
}
set
{
this.selectedColor = value;
OnPropertyChanged("MySelectedColor");
}
}
When control's SelectedColor changes, it should automatically update the MySelectedColor in your VM.

TextBox not triggering PropertyChanged event

I am struggling to figure out why a propertychanged event or lostfocus event is not being triggered when I enter text into a textbox and navigate away from the control.
I am building a Universal Windows Platform app.
I know I'm doing something retarded but I just don't see it.
Any suggestions?
XAML:
<Page
x:Class="xxx.Client.FormPage"
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:viewModels="using:xxx.xxx.ViewModels"
Background="LightBlue"
mc:Ignorable="d">
<Page.Resources>
<Style x:Key="TextBoxStyle" TargetType="TextBox">
<Setter Property="HorizontalAlignment" Value="Stretch" />
<Setter Property="TextAlignment" Value="Center" />
</Style>
</Page.Resources>
<Page.DataContext>
<viewModels:FormViewModel />
</Page.DataContext>
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="auto" />
<RowDefinition Height="auto" />
<RowDefinition Height="auto" />
<RowDefinition Height="*" />
<RowDefinition Height="auto" />
</Grid.RowDefinitions>
<TextBox Grid.Row="0" Text="{Binding InstructorNameInput}" Style="{StaticResource TextBoxStyle}"
PlaceholderText="Instructor Name" />
<TextBox Grid.Row="1" Text="{Binding InstructorIdInput}" Style="{StaticResource TextBoxStyle}"
PlaceholderText="Instructor Id" />
<TextBox Grid.Row="2" Text="{Binding CourseInput}" Style="{StaticResource TextBoxStyle}"
PlaceholderText="Course" />
<Button Grid.Row="4" Content="Accept" Command="{Binding Submit}"
HorizontalAlignment="Stretch"
Foreground="Black" />
</Grid>
</Page>
ViewModel:
public partial class FormViewModel : ViewModelBase
{
public FormViewModel()
{
InstructorName = new RequiredField("Instructor's Name:");
InstructorId = new RequiredField("Instructor's Employee#:");
Course = new RequiredField("Course:");
var courses = CourseFactory.Produce();
var administration = new Administration(courses, null);
Submit = new DelegateCommand(_=> OnSubmit(), CanSubmit);
}
string _instructorNameInput = null;
public string InstructorNameInput
{
get { return _instructorNameInput; }
set
{
if (_instructorNameInput != value)
{
_instructorNameInput = value;
OnNotifyPropertyChanged();
}
}
}
string instructorIdInput = null;
public string InstructorIdInput
{
get { return instructorIdInput; }
set
{
if (instructorIdInput != value)
{
instructorIdInput = value;
OnNotifyPropertyChanged();
}
}
}
string courseInput = null;
public string CourseInput
{
get { return courseInput; }
set
{
if (courseInput != value)
{
courseInput = value;
OnNotifyPropertyChanged();
}
}
}
public RequiredField InstructorName { get; }
public RequiredField InstructorId { get; }
public RequiredField Course { get; }
public ObservableCollection<RequiredField> RequiredFields { get; } = new ObservableCollection<RequiredField>();
}
ViewModel.internal:
public partial class FormViewModel
{
static void OnSubmit()
{
var adminsistration = new Administration();
}
bool CanSubmit(object obj) => !GetUnsatisfied().Any();
IEnumerable<RequiredField> GetUnsatisfied()
{
if (string.IsNullOrEmpty(InstructorIdInput))
{
RequiredFields.Add(InstructorId);
}
else
{
var result = 0;
var isNumeric = int.TryParse(InstructorIdInput, out result);
if (!isNumeric)
{
RequiredFields.Add(new RequiredField(InstructorId.About, "Instructor ID must be numeric"));
}
}
if (string.IsNullOrEmpty(InstructorNameInput))
{
RequiredFields.Add(InstructorName);
}
if (string.IsNullOrEmpty(CourseInput))
{
RequiredFields.Add(Course);
}
return RequiredFields;
}
}
The default binding mode for UWP as MSDN says:
The default is OneWay.
Set it to TwoWay:
<TextBox Grid.Row="0" Text="{Binding InstructorNameInput, Mode=TwoWay}" .../>

How to Track the Current Column Name and Sort Direction In WPF MVVM DataGrid

I need to track the Current Column Name and Sort Direction In WPF MVVM DataGrid. I know how to do it in code behind. Plase see the code as follows:
private void columnHeader_Click(object sender, RoutedEventArgs e)
{
var columnHeader = sender as DataGridColumnHeader;
if (columnHeader != null)
{
columnName = ((DataGridColumnHeader)sender).Content.ToString();
ListSortDirection sortDirection = (((DataGridColumnHeader)sender).SortDirection != ListSortDirection.Ascending) ?
ListSortDirection.Ascending : ListSortDirection.Descending;
txb1.Text = columnName;
txb2.Text = sortDirection.ToString();
}
}
However, I am blocked in MVVM. In the View Model, I wrote codes in method sort() in SortCommand, but they did not work. I would appreciate if any one can help. Below are three files.
1) Xaml
<Window x:Class="SortSampleMVVM1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"
xmlns:se="clr-namespace:Microsoft.Expression.Interactivity.Core;assembly=Microsoft.Expression.Interactions"
Title="MainWindow" Height="350" Width="525">
<Grid>
<DataGrid x:Name="Test"
ItemsSource="{Binding}"
AutoGenerateColumns="False" >
<DataGrid.ColumnHeaderStyle>
<Style TargetType="{x:Type DataGridColumnHeader}">
<Setter Property="Command"
Value="{Binding SortCommand}"/>
<Setter Property="CommandParameter"
Value="{Binding Path=Content, RelativeSource={RelativeSource Self}}"/>
<Style.Triggers>
<Trigger Property="IsPressed" Value="True">
<Setter Property="Background" Value="Red" />
</Trigger>
</Style.Triggers>
</Style>
</DataGrid.ColumnHeaderStyle>
<DataGrid Name="dataGrid1" AutoGenerateColumns="False" ItemsSource="{Binding ViewSource.View}" >
<DataGrid.Columns>
<DataGridTextColumn Header="ID" Binding="{Binding ID }"
SortDirection="Descending" />
<DataGridTextColumn Header="firstName" Binding="{Binding firstName}"/>
<DataGridTextColumn Header="lastName" Binding="{Binding lastName}"/>
</DataGrid.Columns>
</DataGrid>
<Label Content="Column Name" HorizontalAlignment="Left" Margin="100,166,0,0" VerticalAlignment="Top"/>
<TextBox HorizontalAlignment="Left" Height="23" Margin="250,169,0,0" TextWrapping="Wrap" Name="txb1" Text="{Binding ColumnName}" VerticalAlignment="Top" Width="150" />
<Label Content="Sorting direction" HorizontalAlignment="Left" Margin="100,229,0,0" VerticalAlignment="Top"/>
<TextBox HorizontalAlignment="Left" Height="23" Margin="250,232,0,0" TextWrapping="Wrap" Name="txb2" Text="{Binding SortDirection}" VerticalAlignment="Top" Width="150" />
<Button Content="Refresh" Name="btnRefresh1" HorizontalAlignment="Left" Margin="140,273,0,0" VerticalAlignment="Top" Width="75" Command="{Binding Refresh1Command}" />
<Button Content="Refresh Keep Sort" Name="btnRefresh2" HorizontalAlignment="Left" Margin="282,273,0,0" VerticalAlignment="Top" Width="125" Command="{Binding Refresh2Command}" />
</Grid>
</Window>
2) Code behind
using System.Windows;**strong text**
using System.Collections.ObjectModel;
using System.Collections.Generic;
namespace SortSampleMVVM1
{
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
DataContext = new SortViewModel();
}
}
}
3) View Model
using System;
using System.ComponentModel;
using System.Windows.Input;
using System.Windows.Controls.Primitives;
using System.Windows;
using System.Windows.Data;
using System.Collections.ObjectModel;
namespace SortSampleMVVM1
{
class SortViewModel: INotifyPropertyChanged
{
public CollectionViewSource ViewSource { get; set; }
public ObservableCollection<MyData> Collection {get; set;}
private string _columnName;
private ListSortDirection _sortDirection;
private ICommand _sortCommand;
private ICommand _refresh1Command;
private ICommand _refresh2Command;
public SortViewModel ()
{
this.Collection = new ObservableCollection<MyData>();
Collection.Add(new MyData(1, "David", "Lee"));
Collection.Add(new MyData(2, "John", "kim"));
Collection.Add(new MyData(3, "Michael", "Wadsworth"));
Collection.Add(new MyData(4, "Chris", "Smith"));
Collection.Add(new MyData(5, "Peter", "Chen"));
Collection.Add(new MyData(6, "Jonas", "Zhang"));
this.ViewSource = new CollectionViewSource();
ViewSource.Source = this.Collection;
}
public event PropertyChangedEventHandler PropertyChanged;
public string ColumnName
{
get { return _columnName; }
set
{
_columnName = value;
OnPropertyChanged("ColumnName");
}
}
public ListSortDirection SortDirection
{
get { return _sortDirection; }
set
{
_sortDirection = value;
OnPropertyChanged("SortDirection");
}
}
protected void OnPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
{
PropertyChanged(this,
new PropertyChangedEventArgs(propertyName));
}
}
#region SortCommand
public ICommand SortCommand
{
get
{
if (_sortCommand == null)
{
_sortCommand = new RelayCommand(param => this.sort(),
null);
}
return _sortCommand;
}
}
private void sort()
{
//var columnHeader = (object)sender as DataGridColumnHeader;
//if (columnHeader != null)
//{
// _columnName = ViewSource.GetValuecolumnName ((DataGridColumnHeader)sender).Content.ToString();
// ListSortDirection sortDirection = (((DataGridColumnHeader)sender).SortDirection != ListSortDirection.Ascending) ?
// ListSortDirection.Ascending : ListSortDirection.Descending;
//}
}
#endregion
#region Refresh1Command
public ICommand Refresh1Command
{
get
{
if (_refresh1Command == null)
{
_refresh1Command = new RelayCommand(param => this.Refresh1(),
null);
}
return _refresh1Command;
}
}
private void Refresh1()
{
ViewSource.SortDescriptions.Clear();
_columnName = "firstName";
_sortDirection = ListSortDirection.Descending;
ViewSource.SortDescriptions.Add(new SortDescription(_columnName, _sortDirection));
ViewSource.View.Refresh();
}
#endregion
#region Refresh2Command
public ICommand Refresh2Command
{
get
{
if (_refresh2Command == null)
{
_refresh2Command = new RelayCommand(param => this.Refresh2(),
null);
}
return _refresh2Command;
}
}
private void Refresh2()
{
ViewSource.SortDescriptions.Clear();
ViewSource.SortDescriptions.Add(new SortDescription(_columnName, _sortDirection));
ViewSource.View.Refresh();
}
#endregion
}
}
You can use following styling to get the column header.
<Style TargetType="{x:Type DataGridColumnHeader}">
<Setter Property="Command"
Value="{Binding DataContext.MyCommand}"/>
<Setter Property="CommandParameter"
Value="{Binding Path=Content, RelativeSource={RelativeSource Self}}"/>
<Style.Triggers>
<Trigger Property="IsPressed" Value="True">
</Trigger>
</Style.Triggers>
</Style>
</DataGrid.ColumnHeaderStyle>
You have to create the Command 'MyCommand' in your view model. then as the parameter of your execute method you will get column header name.

Why are the datagrid delete command buttons disabled?

I have a DataGrid where each row has a delete button. If I set the Command="Delete" attribute on the Delete button element in XAML, the button is disabled at runtime. Why??
XAML:
<Page x:Class="AxureExport.TargetPage"
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:AxureExport"
mc:Ignorable="d"
d:DesignHeight="300" d:DesignWidth="400"
Title="Define Export Targets"
Loaded="Page_Loaded">
<Page.Resources>
<Style TargetType="{x:Type DataGridCell}">
<EventSetter Event="PreviewMouseLeftButtonDown"
Handler="DataGridCell_PreviewMouseLeftButtonDown" />
</Style>
</Page.Resources>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="7" />
<ColumnDefinition Width="65" />
<ColumnDefinition Width="458*" />
<ColumnDefinition Width="47" />
<ColumnDefinition Width="10" />
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="7" />
<RowDefinition Height="63*" />
</Grid.RowDefinitions>
<!-- target file -->
<TextBlock Name="textBlock3"
Text="2. Select the location where you want to save the string files:"
Height="23"
HorizontalAlignment="Left"
Margin="5,0,0,0"
VerticalAlignment="Top"
Grid.Row="2"
Grid.Column="1"
Grid.ColumnSpan="4"
Width="441" />
<TextBlock Name="textBlock4"
Text="(Warning: This tool overwrites files in the target folder.)"
Height="16"
HorizontalAlignment="Left"
Margin="54,15,0,0"
VerticalAlignment="Top"
Width="256"
FontStyle="Italic"
FontWeight="Light"
FontSize="10"
Grid.Row="2"
Grid.Column="1"
Grid.ColumnSpan="2" />
<TextBlock Name="textBlock5"
Text="Target:"
Height="23"
HorizontalAlignment="Left"
Margin="22,30,0,238"
VerticalAlignment="Center"
Grid.Row="1"
Grid.Column="1" />
<!-- ExportTargets Datagrid -->
<DataGrid Name="ExportTargets"
AutoGenerateColumns="False"
Grid.Column="2"
Grid.Row="1"
Margin="0,71,0,63"
ItemsSource="{Binding Path=., Mode=TwoWay}"
SelectionUnit="Cell"
GridLinesVisibility="None"
RowDetailsVisibilityMode="Collapsed"
CanUserReorderColumns="False"
CanUserResizeColumns="False"
CanUserResizeRows="False"
RowHeaderWidth="40"
IsSynchronizedWithCurrentItem="True"
HorizontalScrollBarVisibility="Disabled"
CanUserAddRows="True"
CanUserDeleteRows="True">
<DataGrid.Resources>
<SolidColorBrush x:Key="{x:Static SystemColors.HighlightBrushKey}"
Color="Transparent" />
<SolidColorBrush x:Key="{x:Static SystemColors.ControlBrushKey}"
Color="Transparent" />
<SolidColorBrush x:Key="{x:Static SystemColors.HighlightTextBrushKey}"
Color="Black" />
<SolidColorBrush x:Key="{x:Static SystemColors.ControlTextBrushKey}"
Color="Black" />
</DataGrid.Resources>
<DataGrid.Columns>
<DataGridCheckBoxColumn Binding="{Binding IsXML, Mode=TwoWay}"
Header="XML"
CanUserSort="False"
CanUserReorder="False" />
<DataGridCheckBoxColumn Binding="{Binding IsProperty, Mode=TwoWay}"
Header="Property"
CanUserSort="False"
CanUserReorder="False" />
<DataGridTextColumn Binding="{Binding FolderName, Mode=TwoWay}"
Header="Folder"
Width="*"
CanUserReorder="False"
IsReadOnly="False" />
<DataGridTemplateColumn Header="Browse">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<Button Name="Browse"
Command="{Binding BrowseCommand}"
HorizontalAlignment="Center"
Width="20">...</Button>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
<DataGridTemplateColumn Header="Delete" IsReadOnly="True">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<Button Name="Delete"
Command="{x:Static DataGrid.DeleteCommand}"
HorizontalAlignment="Center"
Width="20"
IsEnabled="True">X</Button>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
</DataGrid.Columns>
</DataGrid>
<Button Name="NextButton"
Content="Next"
Grid.Column="2"
Grid.ColumnSpan="2"
Grid.Row="1"
Margin="0,0,2,12"
Width="100"
Height="40"
HorizontalAlignment="Right"
VerticalAlignment="Bottom"
Click="NextButton_Click" />
</Grid>
</Page>
Code-behind:
// DataTable
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
namespace AxureExport {
/// <summary>
/// Interaction logic for TargetPage.xaml
/// </summary>
public partial class TargetPage : Page {
FrameWindow _frame;
//ExportTargetInfos _eti;
public TargetPage(FrameWindow frame) {
InitializeComponent();
_frame = frame;
_frame.ExportTargets = new ExportTargetInfos(Properties.Settings.Default.ExportTargetHistory);
this.DataContext = _frame.ExportTargets;
}
//
// enable editing on single-click
private void DataGridCell_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e) {
DataGridCell cell = sender as DataGridCell;
if (!cell.IsEditing) {
if (!cell.IsFocused)
cell.Focus();
if (!cell.IsSelected)
cell.IsSelected = true;
}
}
private void Page_Loaded(object sender, RoutedEventArgs e) {
}
private void NextButton_Click(object sender, RoutedEventArgs e) {
Properties.Settings.Default.ExportTargetHistory = _frame.ExportTargets.GetExportTargets();
_frame.NavigateTo(typeof(ExportPage));
}
}
}
ViewModel:
using System;
using System.Collections.ObjectModel; // ObservibleCollection<>
using System.Collections.Specialized; // StringCollection
using System.ComponentModel; // INotifyPropertyChanged
namespace AxureExport {
public class ExportTargetInfos : ObservableCollection<ExportTargetInfo> {
const char _SEP = '|'; // field seperator character
// default constructor
public ExportTargetInfos() : base() {
}
// copy constructors
public ExportTargetInfos(ExportTargetInfos etis) : base() {
if (etis == null) return;
foreach (ExportTargetInfo eti in etis) {
this.Add(new ExportTargetInfo(eti.FolderName, eti.IsXML, eti.IsProperty));
}
}
public ExportTargetInfos(StringCollection sc) : base() {
if (sc == null) return;
foreach (string s in sc)
Add(ParseExportTarget(s));
}
public StringCollection GetExportTargets() {
StringCollection sc = new StringCollection();
foreach (ExportTargetInfo et in this)
sc.Add(BuildExportTarget(et));
return sc;
}
// create a string from an ExportTarget (for persistance)
private static string BuildExportTarget(ExportTargetInfo et) {
return et.FolderName + _SEP + et.IsXML.ToString() + _SEP + et.IsProperty.ToString();
}
// create an ExportTarget from an unparsed string (for persistance)
private static ExportTargetInfo ParseExportTarget(string s) {
int count = s.Split(_SEP).Length - 1;
string[] items = s.Split(new[] { _SEP }, StringSplitOptions.None);
string name = (count < 1 ? String.Empty : items[0]);
bool isXML = (count > 0 ? Convert.ToBoolean(items[1]) : false);
bool isProp = (count > 1 ? Convert.ToBoolean(items[2]) : false);
return new ExportTargetInfo(name, isXML, isProp);
}
}
//
// represents an export target (folder plus options) in it's parsed form
public class ExportTargetInfo : INotifyPropertyChanged {
public event PropertyChangedEventHandler PropertyChanged;
public IDelegateCommand BrowseCommand { protected set; get; }
// default constructor is needed to enable datagrid to add rows
public ExportTargetInfo() {
_folderName = String.Empty;
_isXML = false;
_isProperty = false;
this.BrowseCommand = new DelegateCommand(ExecuteBrowse, CanExecuteBrowse);
}
public ExportTargetInfo(string targetFolderName, bool isXML, bool isProperties) {
_folderName = targetFolderName;
_isXML = isXML;
_isProperty = isProperties;
this.BrowseCommand = new DelegateCommand(ExecuteBrowse, CanExecuteBrowse);
}
private string _folderName;
public string FolderName {
get { return _folderName; }
set { SetProperty<string>(ref _folderName, value, #"FolderName"); }
}
private bool _isXML;
public bool IsXML {
get { return _isXML; }
set { SetProperty<bool>(ref _isXML, value, #"IsXML"); }
}
private bool _isProperty;
public bool IsProperty {
get { return _isProperty; }
set { SetProperty<bool>(ref _isProperty, value, #"IsProperty"); }
}
// browse button for selected row clicked
void ExecuteBrowse(object param) {
// use WPF-WinForms interop (:-p)
var folderDialog = new System.Windows.Forms.FolderBrowserDialog();
folderDialog.Description = "Please designate the target folder";
folderDialog.SelectedPath = FolderName;
folderDialog.ShowNewFolderButton = true;
if (folderDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
FolderName = folderDialog.SelectedPath;
}
bool CanExecuteBrowse(object param) {
return true;
}
protected bool SetProperty<T>(ref T storage, T value, string propertyName = null) {
if (object.Equals(storage, value))
return false;
storage = value;
OnPropertyChanged(propertyName);
return true;
}
protected void OnPropertyChanged(string propertyName) {
if (PropertyChanged != null)
PropertyChanged( this, new PropertyChangedEventArgs(propertyName));
}
}
}
Does anyone have insight as to what's the cause?
This isn't a solution, but through trial & error I discovered the disabled delete button behavior is caused by the SelectionUnit="Cell" setting in the DataGrid. Setting it to FullRow enables the delete row button.
<Button Name="NextButton" isEnable = "true" />