Quantcast
Channel: Windows Presentation Foundation (WPF) forum
Viewing all 18858 articles
Browse latest View live

How to sort keys in ResourceDictionary in xaml in wpf?

$
0
0

Hi EveryOne,

              I need to sort the keys in ResourceDictionary in xaml. I tried with sorting using SortedList and stored using XamlWriter.Save. but it storing in Unsorted Order in xaml. Can any one help me to solve the problem?

Ex:

        <ResourceDictionary>

              <sys:string x:Key="Subtraction">Subtraction</sys:string>

              <sys:string x:Key="Add">ADD</sys:string>

              <sys:string x:Key="Multiply">Multiplication</sys:string>

        </ResourceDictionary>

Thanks,

Stalin Raj.


Chaining (Dependency) Properties to nested control's ViewModel

$
0
0
Hi, I have a ListBox with a GroupStyle that contains another ListBox. Now I want to filter the Items of this nested ListBox depending on the group name of the parent ListBox.

In the code below I tried to chain the "GroupItem.Name.Name" property to the "GroupName" property of the ViewModel of the nested ListBox, but this didn't work out so well.

Essentially the "GroupNameIn" Property is filled by the GroupItems' name(the TextBlock Text) and then sets the "GroupNameOut" Property to the same value in the "PropertyChangedCallback". 

But when the setter of the "GroupName" Property of the "NestedItemsViewModel" gets called, the value is always null. (The NestedItemsDataContext is a DP of the parent ListBox). 

Are there any mistakes in my approach or is there even a simpler/better way to achieve this behavior?

I would be very grateful if someone could point me in the right direction.


GroupStyle of the parent ListBox:

<Style x:Key="MyListBoxGroupStyle" TargetType="{x:Type GroupItem}"><Setter Property="Template"><Setter.Value><ControlTemplate TargetType="{x:Type GroupItem}"><StackPanel Name="container" Width="Auto" Orientation="Vertical"><TextBlock Name="groupNameTextBlock" Text="{Binding Path=Name.Name}"/><ItemsPresenter/><MyNestedListBox  
                          DataContext="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type ListBox}}, Path=NestedItemsDataContext}"
                          ItemsSource="{Binding NestedItems}"
                          GroupNameIn="{Binding ElementName=groupNameTextBlock, Path=Text}"
                          GroupNameOut="{Binding Path=GroupName, Mode=OneWayToSource, UpdateSourceTrigger=PropertyChanged}"</StackPanel></ControlTemplate></Setter.Value></Setter></Style>

The nested ListBox:

public class MyNestedListBox : ListBox
{
    static MyNestedListBox()
    {
        DefaultStyleKeyProperty.OverrideMetadata(typeof(MyNestedListBox), new FrameworkPropertyMetadata(typeof(MyNestedListBox)));
    }

    public string GroupNameIn
    {
        get { return (string)GetValue(GroupNameInProperty); }
        set { SetValue(GroupNameInProperty, value); }
    }
    public string GroupNameOut
    {
        get { return (string)GetValue(GroupNameOutProperty); }
        set { SetValue(GroupNameOutProperty, value); }
    }

    // DepenencyProperties
    public static readonly DependencyProperty GroupNameInProperty =
        DependencyProperty.Register("GroupNameIn", typeof(string), typeof(MyNestedListBox), new UIPropertyMetadata(null) { PropertyChangedCallback = (obj, target) => 
            {

		MyNestedListBox lb = obj as MyNestedListBox;
                lb.SetValue(GroupNameOutProperty, target.NewValue);
                // lb.GetBindingExpression(MyNestedListBox.GroupNameOutProperty).UpdateSource();   // doesn't seem to have an effect
            } 
        });

    public static readonly DependencyProperty GroupNameOutProperty =
        DependencyProperty.Register("GroupNameOut", typeof(string), typeof(MyNestedListBox), new UIPropertyMetadata(null));
}

ViewModel bound to the nested ListBox:

public class NestedItemsViewModel : ViewModelBase
{
    private string _groupName;

    public ObservableCollection<NestedItem> NestedItems { get; set; }
    public string GroupName 
    {
        get 
        {
            return _groupName;
        }
        set
        {
            _groupName = value;
            OnPropertyChanged(() => GroupName);
        }
    }

    public NestedItemsViewModel()
    {
        NestedItems = new ObservableCollection<NestedItem>();
    }
}


WPF - Speeding up RTF Loading Code

$
0
0

Hello all,

I'm working on an update for one of my programs, and the Load function that loads the user's information is lagging for maybe 1 or two seconds. In my application, the user can click buttons and scroll through pages. This leads to a slightly annoying experience if the user is scrolling through the pages and the content takes a second or two to load; the scrolling will not be as seamless as I'd like it to be. In the past, this wasn't an issue because I only had 11 RichTextBoxes on the main window (and I did it in Windows Forms). Now, I have 21 RichTextBoxes on the interface, and I can't seem to find a way to increase the loading speed.

I am fully aware of the System.Threading.Thread options; however, I want to allocate some parts of the loading code to different threads but wait for the entire process to complete before anything else happens. Using an entirely new background thread to do the loading wouldn't work very well because the user could navigate to a new page on the UI thread, and the background thread (not having completed yet) could potentially load the previous page's information a little late, thereby leaving the user with the wrong page information.

Here's my synchronous loading code that is running just a little slower than I'd hope it would:

TextRange RtfText;

foreach (RichTextBox box in RichTextBoxList)
{
    using (FileStream stream = new FileStream(FilePath + box.Name.Substring(3) + ".rtf", FileMode.Open, FileAccess.Read))
    {
        RtfText = new TextRange(box.Document.ContentStart, box.Document.ContentEnd);
        RtfText.Load(stream, DataFormats.Rtf);
    }
}


As you can see, I go through each RichTextBox in the list, open a file stream to the correct file name, and then load it into a TextRange. To speed this up, I thought I would use Parallel Tasks (http://msdn.microsoft.com/en-us/library/ff963549), but it seems as though I'm still running into issues with that. I've tried using two slightly different methods to use parallel tasks:

1) Parallel.For

Parallel.For(0, 22, (i) =>
    {
        LoadRTF(FilePath, RichTextBoxList[i]);
    }
);
private void LoadRTF(String FilePath, RichTextBox box)
{
    using (FileStream stream = new FileStream(FilePath + box.Name.Substring(3) + ".rtf", FileMode.Open, FileAccess.Read))
    {
        TextRange RtfText = new TextRange(box.Document.ContentStart, box.Document.ContentEnd);

        RtfText.Load(stream, DataFormats.Rtf);
    }
}

This unfortunately did not work, as I got the following error message: The calling thread cannot access this object because a different thread owns it.

Using the same LoadRTF method as above, I tried a different approach to see if the results would change:

2) Task.Factory

List<Task> tasks = new List<Task>();
RichTextBox TempBox;

foreach (RichTextBox box in main.TextBoxes)
{
    TempBox = box;
                
    tasks.Add(Task.Factory.StartNew(() => LoadRTF(FilePath, TempBox)));
}


Unfortunately, I still got the same error message: The calling thread cannot access this object because a different thread owns it.

A quick google search of this revealed that only the UI thread can access controls and their properties (in this case, Name). I've looked into how I could possibly change my code to accommodate this, but I haven't had any luck so far.

I am wondering if anyone could please give me some guidance on how I can speed up my RTF loading code, however it may be. If someone could assist me with changing my code to use the UI thread so that I will no longer get this persistent error message, that would be great. If you can suggest another, working method of getting this done (even synchronously!), that'd be awesome as well.

My greatest thanks goes out to anyone who takes the time out to lend me a hand!

Sort a WPF ListBox By Search String

$
0
0

Good day,

I would like to sort items in a list box by a search string.

Matched result comes first then sort by alphabetical order.

e.g. My List

dog, cat, bull, door, table, bird, orange

and my keyword is 'do'

RESULT:

dog, door, bird, bull, cat, orange, table

Any ideas, thanks.

How to insert a image on cursor in wpf?

$
0
0

Hi,

 

I'm with problems... I dont know how to insert a on cursor.

I have images of type png and i would like put on cursor...

 

Does anybody know how to make it?

{DependencyProperty.UnsetValue}' is not a valid value for the 'System.Windows.Documents.TextElement.Foreground' property on a Setter.

$
0
0

I have created a ComboBoxStyle.

=> When I apply this to the combo boxes and UI becomes unstable with the below error.

<Setter Property="Foreground" Value="{StaticResource OutsideFontBrush}"/>

I get below error -

Error 11 '{DependencyProperty.UnsetValue}' is not a valid value for the 'System.Windows.Documents.TextElement.Foreground' property on a Setter.

Note : OutsideFontBrush Resource exists. I have made sure that all the resources used in this style exist.

=> I tried changing the StaticResource to DynamicResource. But it doesnt fix it.

=> When I try to harcode the Foreground property to "Black". I get "Object reference not set to an object" error.

<Setter Property="Foreground" Value="Black"/>

Not sure how to fix this. Any Ideas ?

Below is the style =>

<Style x:Key="ComboBoxStyle" TargetType="{x:Type ComboBox}" BasedOn="{StaticResource ErrorTemplateStyle}"><Setter Property="SnapsToDevicePixels" Value="true"/><Setter Property="Foreground" Value="{StaticResource OutsideFontBrush}"/><Setter Property="FontWeight" Value="Normal"/><Setter Property="Template"><Setter.Value><ControlTemplate TargetType="{x:Type ComboBox}"><ControlTemplate.Resources><Storyboard x:Key="FocusedOn"><DoubleAnimationUsingKeyFrames BeginTime="00:00:00" Storyboard.TargetName="FocusVisualElement" Storyboard.TargetProperty="(UIElement.Opacity)"><SplineDoubleKeyFrame KeyTime="00:00:00.1000000" Value="1"/></DoubleAnimationUsingKeyFrames></Storyboard><Storyboard x:Key="FocusedOff"><DoubleAnimationUsingKeyFrames BeginTime="00:00:00" Storyboard.TargetName="FocusVisualElement" Storyboard.TargetProperty="(UIElement.Opacity)"><SplineDoubleKeyFrame KeyTime="00:00:00.3000000" Value="0"/></DoubleAnimationUsingKeyFrames></Storyboard></ControlTemplate.Resources><Grid Background="{commonMarkup:ColorExtension Color={StaticResource ControlBackgroundColor}}"><ContentPresenter HorizontalAlignment="Left"
                                          Margin="3,3,23,3"
                                          x:Name="ContentSite"
                                          VerticalAlignment="Center"
                                          Content="{TemplateBinding SelectionBoxItem}"
                                          ContentTemplate="{TemplateBinding SelectionBoxItemTemplate}"
                                          ContentTemplateSelector="{TemplateBinding ItemTemplateSelector}"
                                          IsHitTestVisible="True"/><ToggleButton Template="{DynamicResource ComboBoxToggleButton}"
                                      x:Name="ToggleButton"
                                      Focusable="false"
                                      IsChecked="{Binding Path=IsDropDownOpen, Mode=TwoWay, RelativeSource={RelativeSource TemplatedParent}}"
                                      ClickMode="Press"/><TextBox Visibility="Hidden"
                                 Template="{DynamicResource ComboBoxTextBox}"
                                 HorizontalAlignment="Left"
                                 Margin="3,3,23,3"
                                 x:Name="PART_EditableTextBox"
                                 Style="{x:Null}"
                                 VerticalAlignment="Center"
                                 Focusable="True"
                                 Background="Transparent"
                                 IsReadOnly="{TemplateBinding IsReadOnly}"/><Rectangle x:Name="DisabledVisualElement"
                                   Fill="{commonMarkup:ColorExtension Color={StaticResource DisabledVisualEmtColor}}"
                                   Opacity="0.25"
                                   RadiusX="4" RadiusY="4"
                                   IsHitTestVisible="True"
                                   Visibility="Collapsed" /><Rectangle x:Name="FocusVisualElement"
                                   Margin="-1"
                                   Stroke="{StaticResource SelectedStrokeBrush}" StrokeThickness="1"
                                   RadiusX="4" RadiusY="4"
                                   IsHitTestVisible="True" Opacity="0"/><Popup IsOpen="{TemplateBinding IsDropDownOpen}"
                               Placement="Bottom"
                               x:Name="Popup"
                               Focusable="False"
                               AllowsTransparency="False" 
                               PopupAnimation="Slide"><Grid MaxHeight="{TemplateBinding MaxDropDownHeight}"
                                  MinWidth="{TemplateBinding ActualWidth}"
                                  x:Name="DropDown"
                                  SnapsToDevicePixels="True"><Border x:Name="DropDownBorder"
                                        Background="{commonMarkup:ColorExtension Color={StaticResource ControlBackgroundColor}}"
                                        BorderBrush="{StaticResource TextBoxNorm}" BorderThickness="1" 
                                        CornerRadius="1,1,1,1"><ScrollViewer Margin="4,6,4,6"
                                                  SnapsToDevicePixels="True"
                                                  HorizontalScrollBarVisibility="Auto" VerticalScrollBarVisibility="Auto"
                                                  CanContentScroll="True"><ItemsPresenter KeyboardNavigation.DirectionalNavigation="Contained"/></ScrollViewer></Border></Grid></Popup></Grid><ControlTemplate.Triggers><Trigger Property="IsFocused" Value="True"><Trigger.ExitActions><BeginStoryboard Storyboard="{StaticResource FocusedOff}" x:Name="FocusedOff_BeginStoryboard"/></Trigger.ExitActions><Trigger.EnterActions><BeginStoryboard Storyboard="{StaticResource FocusedOn}"/></Trigger.EnterActions></Trigger><Trigger Property="HasItems" Value="false"><Setter Property="MinHeight" Value="95" TargetName="DropDownBorder"/></Trigger><Trigger Property="IsEnabled" Value="false"><Setter Property="Foreground" Value="{DynamicResource DisabledForeColorBrush}"/><Setter Property="Visibility" TargetName="DisabledVisualElement" Value="Visible"/></Trigger><Trigger Property="IsGrouping" Value="true"><Setter Property="ScrollViewer.CanContentScroll" Value="false"/></Trigger><Trigger Property="AllowsTransparency" SourceName="Popup" Value="true"><Setter Property="CornerRadius" Value="1" TargetName="DropDownBorder"/><Setter Property="Margin" Value="0,2,0,0" TargetName="DropDownBorder"/></Trigger><Trigger Property="IsEditable" Value="true"><Setter Property="IsTabStop" Value="false"/><Setter Property="Visibility" Value="Visible" TargetName="PART_EditableTextBox"/><Setter Property="Visibility" Value="Hidden" TargetName="ContentSite"/></Trigger></ControlTemplate.Triggers></ControlTemplate></Setter.Value></Setter></Style>


Ashish Dhyani

WPF listbox image binding

$
0
0

Good morning,

I already implemented a application that loads images from a directory to a listbox. All ok but the loading takes about 5 seconds to display around 20-30 images. Is there a way to decrease the time needed for the images to be loaded. Or is it correct to display an loading image in front of the UI so the user knows images are loading? Thank you in advance for the help. Below is my xaml code for the listbox.

<ListBox Name="Images" ListBox.SelectionChanged="lstImagesChange_Click" Grid.Column="1" 
                 ScrollViewer.HorizontalScrollBarVisibility="Disabled" VirtualizingStackPanel.IsVirtualizing="false"
                 VirtualizingStackPanel.VirtualizationMode="Recycling" ScrollViewer.IsDeferredScrollingEnabled="True"><ListBox.Resources><Style x:Key="{x:Type ScrollBar}" TargetType="{x:Type ScrollBar}"><Style.Triggers><Trigger Property="Orientation" Value="Vertical"><Setter Property="Width" Value="20"/><Setter Property="Height" Value="Auto" /></Trigger></Style.Triggers></Style></ListBox.Resources><ListBox.ItemsPanel><ItemsPanelTemplate><WrapPanel IsItemsHost="True" Orientation="Horizontal" FlowDirection="LeftToRight" /></ItemsPanelTemplate></ListBox.ItemsPanel><ListBox.ItemTemplate><DataTemplate><Border BorderThickness="2" BorderBrush="#bb62d8" Background="Black" Width="200" Height="200" Margin="5,5,10,5" CornerRadius="10"><Image Source="{Binding Path=Path, Converter={StaticResource UriToBitmapConverter}}" Tag="{Binding ImageID}" /></Border></DataTemplate></ListBox.ItemTemplate></ListBox>

and below is the code loading the images

if (!(images == null))
            {
                Images.ItemsSource = images;
            }

WPF DatagridTextColumn not changing immediately when a DataGridComboBoxColumn’s selection is changed

$
0
0

Hi

I have 2 Tables in a typical Master-Detail relationship :

1) AcctGrps is the Master table. It has 2 columns : AcctGrpCd and AcctGrpName, with AcctGrpCd being the PK.

2) Accts is the Detail table. It has 3 columns : AcctCd, AcctName and AcctGrpCd, with AcctCd being the PK. Thus, each Account has a single AcctGrpCd.

I have a WPF DataGrid in my Window, which displays the Accts data, in the following DataGridColumns :

1) AcctCd  DataGridTextColumn

2) AcctName  DataGridTextColumn

3) AcctGrpCd  DataGridTextColumn

4) AcctGrpName  DataGridComboBoxColumn : This column should be bound such that it displays the AcctGrpName from the AcctGrps table, corresponding to the AcctGrpCd in each Row.

I am retrieving both Tables from the DB, and returning them in DataTable.DefaultView objects, dynamically. (Since the tables are anyway created at runtime, I am not using an ObjectDataProvider.) The DataTable.DefaultView property is of type DataView, which implements the IbindingList interface and therefore provides Change Notifications.

Everything is working perfectly. The only problem is that when I change the selection in the AcctGrpName DataGridComboBoxColumn, the value displayed in the AcctGrpCd DataGridTextColumn changes only when I click on ANOTHER row. I would like the displayed AcctGrpCd to change IMMEDIATELY when the selection is changed in the AcctGrpName DataGridComboBoxColumn. How can I do this ?

The code is shown below :

<Window x:Class="WDataGridAcctsWGrpNames"
   ... ><DockPanel><StackPanel 
           DockPanel.Dock="Top" 
           Orientation="Horizontal"><Button 
                Click="btLoad_Click" 
                Content="Load" Height="23" 
	       Margin="5" 
                Name="btLoad" 
                Width="75" /></StackPanel><DataGrid  
            AutoGenerateColumns="False" 
            DataContext="{Binding}" 
            Height="215" 
            DockPanel.Dock="Top" 
            ItemsSource="{Binding}" 
            Margin="10" 
            Name="dgAccts" 
            Width="407"><DataGrid.Columns><DataGridTextColumn 
                    Header="Acct No" 
                    Binding="{Binding AcctNo}" /><DataGridTextColumn 
                    Header="Acct Name" 
                    Binding="{Binding AcctName}" /><DataGridTextColumn 
                    Header="Acct Grp Cd" 
                    Binding="{Binding AcctGrpCd}" /><DataGridComboBoxColumn 
                    DisplayMemberPath="AcctGrpName" 
                    Header="Acct Group" 
                    ItemsSource="{Binding}" 
                    SelectedValueBinding="{Binding AcctGrpCd}"
                    SelectedValuePath="AcctGrpCd" 
                    x:Name="dgccAcctGrps" /></DataGrid.Columns></DataGrid></DockPanel></Window>
    Private Sub btLoad_Click(
        ByVal sender As System.Object, 
        ByVal e As System.Windows.RoutedEventArgs)
        Try
            ' Disable the Load button.
            btLoad.IsEnabled = False
            ' Display a Wait cursor.
            Me.Cursor = Cursors.Wait
            ' Load Acct Groups data.
            Me.LoadAcctGrps()
            ' Load Accts data.
            Me.LoadAccts()
        Catch ex As Exception
            MessageBox.Show(
              ex.Message,
              ex.GetType.ToString)
        Finally
            ' Enable the Load button.
            btLoad.IsEnabled = True
            ' Display a Default cursor.
            Me.Cursor = Cursors.Arrow
        End Try
    End Sub
    ' Load Acct Groups data.
    Private Sub LoadAcctGrps()…  ' Code to obtain the 
             Acct Groups DataTable …
 
        ' Obtain a reference to the 
          Acct Groups DataTable.
        m_dtAcctGrps = 
              m_dsAcctGrps.Tables(0)
        ' List-Bind the Account Groups 
          DataGridComboBoxColumn to the
	 Account Groups DataTable.
        dgccAcctGrps.ItemsSource = 
               m_dtAcctGrps.DefaultView
    End Sub
    ' Load Accts data.
    Private Sub LoadAccts()
        …  ' Code to obtain the 
             Accts DataTable …
        ' Obtain a reference to the 
          Accts DataTable.
        m_dtAccts = m_dsAccts.Tables(0)
        ' List-bind the Accounts DataGrid to 
          the Accounts DataTable.
        dgAccts.DataContext = 
             m_dtAccts.DefaultView
    End Sub

Please note that DataViews serve as the Binding Source, and they implement the IBindingList interface and therefore already provide Change Notifications.

Perhaps, this problem is being caused because the DataRow’s EndEdit() method is called implicitly, when the user clicks on another Row. I would like to call the EndEdit() method explicitly, but in which event ? The DataGridComboBoxColumn doesn’t provide a SelectionChanged event ! So, in which event can it be called ?

Secondly, does this sort of problem occur if the DataGrid is bound to a List(Of Acct) object and the DataGridComboBoxColumn to a List(Of AcctGrp) object ? I haven’t yet tried this approach and am wondering if this is the standard approach in WPF, rather than binding to a DataView. If so, is it to avoid this kind of a problem ?

Thanks.

Steven



Cannot acces Property settings from a common project

$
0
0

Hello All,

I have a project called Common, and it contains classes and code that is used by three other projects. I have a Settings.setting file, and would like to share that along the three projects too, but when I try to access it by calling:

Common.Properties.Settings.Default.Save(); 

this fails with a error message that says:

The property cannot be used in this context because the set accessor is inaccessible.

So my question is:

1. Is the Settings.setting file designed to be used per project and not across projects?

2. If need be for only one Settings.setting file, what are myoptions? Do I have access to the code where the set message is defined, to change it to make it public?

Regards,

Harriet

ListCollectionView CancelEdit throws exception

$
0
0

I have a page. It has a ListCollectionView property. The property is initialized in the ctor via input args before the call to InitializeComponent(). I want to edit the current item. I call MyLcv.EditItem(MyLcv.CurrentItem). To accept changes, I call MyLcv.CommitEdit(). It works. To cancel changes, I call MyLcv.CancelEdit(). This throws an InvalidOperationException, saying "CancelEdit is not supported for the current edit item." Any Ideas?

Bill


Bill Swartz

How to make the camera view and skeleton tracking overlay each other

$
0
0
I have one canvas which contains the Skelton and one image which contains the camera view . However I can't merge them together . As in I need the skeleton to be able to show overlay of the camera view so that can see both together on one screen instead of two . Isit possible to Do that ? Or I have one more program which works the same way however I use image to image also facing the same problem
<Window x:Class="KinectSkeletonViewer.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="Skeleton Viewer" SizeToContent="WidthAndHeight" Loaded="Window_Loaded" mc:Ignorable="d" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" d:DesignHeight="744" d:DesignWidth="1173"><StackPanel Width="1000" Height="702" MaxWidth="Infinity"><TextBlock FontSize="30" FontStretch="Expanded" FontStyle="Normal" FontWeight="Bold" Foreground="Black" Height="40" Name="textBlock1" Text="Position" Width="376" /><TextBlock Name="StatusTextBlock" Text="Skeleton Status" FontSize="30" Width="375"></TextBlock><TextBlock Name="QualityTextBlock" Text="Quality Display" FontSize="30" Height="60" Width="385"></TextBlock><Canvas Height="261" Name="skeletonCanvas" Width="383"></Canvas><Image Height="238" Name="CameraView" Stretch="Fill" Width="300" /></StackPanel></Window>

Custom cursor from VisualBrush?

$
0
0

Hi,

Is it possible to create a custom cursor from a VisualBrush in any way?

Remove ListCollectionView items does not update UI

$
0
0

Hello guys,

    I have a Datagrid.ItemsSource binded with a ListCollectionView obtained from an objectquery from EF.

    It work's fine, but, when i Add a new items and "undo" (before save) the items still shows on the datagrid.

    The "undo" i do is listCollectionInstance.Remove(theNewItem).

    I've tried to mark it's state as detached or unchanged or something like that but it still shows on the datagrid.

    I've tried also to listCollectionInstance.Refresh() and it does nothing.

    I could and it works, reload all the collection again from the database, but depending on the size of the collection (4k lines* 15 columns) the reload can take a while because i'm accessing a remote datacenter. When i say "a while" i mean it is not acceptable to wait that time to undo something that never went to the server.

   What i really want is to undo the "add new item" before i had even saved it and that that action reflect itself in the datagrid.

many thanks.

    

DragDrop Adorner Template disappears between windows

$
0
0

Hi,

I'm having an issue where my drag drop adorner template is disappearing when dragging from one window to another. The drop performs perfectly correctly but the adorner template is only visable in the window where you stat. As soon as you get to the edge of the window is begins to get clipped. This is dragging from a datagrid in one window to another datagrid in another window. Seems ok as long as the datagrids are in the same window. Is there any way around this?

Regards

Celestrium

RelayCommand in WorkspaceViewModel

$
0
0

Hi,

I am going through the Josh Smith's article "WPF Apps with the Model-View-ViewModel Design Pattern" and it's example solution. I am creating classes and view one-by-one in my new test project, so that I can learn and understand it.

Currently I am stuck with the WorkspaceViewModel class.  When I am trying to declare "RelayCommand _closeCommand;" field it shows in red underline.  When I hover my mouse over it displays the following message:

"The type or namespace name RelayCommand could not be found(are you missing using directive or an assembly reference)".

I have implemented RelayCommand class in project's namespace (exactly as it is in his example) and implemented ViewModelBase.

I do understand that RelayCommand is not in the same namespace as the 'ViewModel' classes, but how does it work in his example ?   I am missing some views, but that shouldn't affect anyway.

Can anyone suggest why his example works and mine does not ?

Thank you


Can't get a ListBox to work on a splash screen?...

$
0
0

Hi,

I download this project Prism Splash Screen Module from CodePlex and I have it working for myMEF application, but I found that only the TextBlock control works.  I can't get aListView, TextBox, ListBox, etc,. to work on the start-up splash screen.

Getting this un-explain error when I Invoke the splash screen view:

You can down load the code and try the same thing to better understand, but here is the code part:

namespace Natsar.Module.SplashScreen
{
    using System.ComponentModel.Composition;

    using Microsoft.Practices.Prism.Logging;
    using Microsoft.Practices.Prism.MefExtensions.Modularity;
    using Microsoft.Practices.Prism.Modularity;
    using Microsoft.Practices.Prism.Events;
    using Microsoft.Practices.ServiceLocation;

    using Natsar.Infrastructure.Interfaces;

    using Events;
    using Views;

    [ModuleExport(typeof(SplashScreenModule), InitializationMode = InitializationMode.OnDemand, DependsOnModuleNames = new string[] { "InfrastructureModule" })]
    public class SplashScreenModule : IModule
    {
        private IEventAggregator EventAggregator { get; set; }
        private IShell Shell { get; set; }
        private AutoResetEvent WaitForCreation { get; set; }

        [ImportingConstructor]
        public SplashScreenModule(IEventAggregator eventAggregator, IShell shell)
        {
            try
            {
                ///ArgumentNullException : need to add excpetion handling
                if (eventAggregator == null)
                {
                    throw new ArgumentNullException("eventAggregator");
                }
                if (shell == null)
                {
                    throw new ArgumentNullException("shell");
                }

                this.EventAggregator = eventAggregator;
                this.Shell = shell;
            }
            catch (Exception msg)
            {
                StringBuilder sMsg = new StringBuilder();

                sMsg.Append("Message: ").Append(msg.Message).AppendLine();
                sMsg.Append("InnerException: ").Append(msg.InnerException).AppendLine();
                sMsg.Append("Source: ").Append(msg.Source).AppendLine();
                sMsg.Append("StackTrace: ").Append(msg.StackTrace).AppendLine();

                ///TODO: Put in logic to send exception
#if (DEBUG)
                Console.WriteLine(sMsg.ToString());
                MessageBox.Show(sMsg.ToString(), this.GetType().ToString());
#endif
            }
        }

        /// <summary>
        /// Notifies the module that it has be initialized.
        /// </summary>
        public void Initialize()
        {
            Debug.WriteLine("SplashScreenModule instantiation");
            Dispatcher.CurrentDispatcher.BeginInvoke(
              (Action)(() =>
                          {
                              Shell.Show();
                              EventAggregator.GetEvent<CloseSplashEvent>().Publish(new CloseSplashEvent());
                          }));

            WaitForCreation = new AutoResetEvent(false);

            ThreadStart showSplash =
              () =>
              {
                  Dispatcher.CurrentDispatcher.BeginInvoke(
                    (Action)(() =>
                                {
                                    SplashScreenView splash = ServiceLocator.Current.GetInstance<SplashScreenView>();
                                    EventAggregator.GetEvent<CloseSplashEvent>().Subscribe(
                                      e => splash.Dispatcher.BeginInvoke((Action)splash.Close),
                                      ThreadOption.PublisherThread, true);

                                    splash.Show();

                                    WaitForCreation.Set();
                                }));

                  Dispatcher.Run();
              };

            var thread = new Thread(showSplash) { Name = "Splash Thread", IsBackground = true };
            thread.SetApartmentState(ApartmentState.STA);
            thread.Start();

            WaitForCreation.WaitOne();
        }
    }
}

I call this from my Bootstrapper.cs:

public class NatsarBootstrapper : MefBootstrapper
{

	#region Private Properties
	private IEventAggregator EventAggregator
	{
		get { return ServiceLocator.Current.GetInstance<IEventAggregator>(); }
	}
	#endregion

	protected override void InitializeModules()
	{
		IModuleManager manager = ServiceLocator.Current.GetInstance<IModuleManager>();
		manager.LoadModule("SplashScreenModule");

		EventAggregator.GetEvent<MessageUpdateEvent>().Publish(new MessageUpdateEvent { Message = "DocumentsModule" });
		manager.LoadModule("DocumentsModule");
	}
...
..
.
}

Is there anything I can do different to make this work?  What I'm doing is showing initialization messages as I load modules and data during start-up.  I want to show each message in a list instead of on a singleTextBlock, just to keep the user amusement.

I can live with the single TextBlock message, but would prefer using a ListBox.


Code is like a box of chocolates!...


Scroll Nested Datagrid inside RowDetailsTemplate

$
0
0

I have the following xaml and c#.

I use DataGrid and RowDetailsTemplate with another DataGrid.

The parent grid with Person information, the child grid has cars owned by the person.

I
got some of this code from another post, I changed it and am looking to
be able to navigate between persons and cars using the up/down arrows.

I am getting all kind of focus issues and not able to move between different persons and cars.

Can anyone tell me what I am doing wrong, and how to accomplish what I want.

Thanks in advance.

XAML----------------------------------------------

<Window x:Class="DataGridEx2.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:DataGridEx2"
Title="MainWindow" Height="350" Width="525">

<Grid>
<Grid.RowDefinitions>
<RowDefinition/>
<RowDefinition Height="40"/>
</Grid.RowDefinitions>
<DataGrid Grid.Row="0"
x:Name="objDatagrid"
ItemsSource="{Binding DataView}"
Background="White"
CanUserAddRows="False"
CanUserDeleteRows="False"
RowDetailsVisibilityMode="Visible"
FontFamily="Arial" FontSize="20"
GridLinesVisibility="All"
IsReadOnly="True"
KeyboardNavigation.TabNavigation="Local"
KeyboardNavigation.DirectionalNavigation="Continue"
ScrollViewer.IsDeferredScrollingEnabled="True"
ScrollViewer.CanContentScroll="False"
IsSynchronizedWithCurrentItem="True"
CanUserSortColumns="False"
SelectedItem="{Binding SelectedPerson,UpdateSourceTrigger=PropertyChanged,Mode=TwoWay}"
IsTabStop="True"
SelectionUnit="FullRow"

AutoGenerateColumns="False" BorderThickness="0"
CanUserReorderColumns="False" CanUserResizeColumns="False"
SelectionMode="Single" CanUserResizeRows="False"
PreviewKeyDown="objDatagrid_PreviewKeyDown"
SelectionChanged="objDatagrid_SelectionChanged" >
<DataGrid.RowDetailsTemplate >
<DataTemplate DataType="{x:Type local:Person}">
<DataGrid x:Name="objInnerDatagrid" Height="Auto" Padding="0"
ItemsSource="{Binding Cars}"
Background="White"
CanUserAddRows="False"
CanUserDeleteRows="False"
RowDetailsVisibilityMode="Visible"
FontFamily="Arial" FontSize="20"
GridLinesVisibility="All"
IsReadOnly="True"
KeyboardNavigation.TabNavigation="Local"
ScrollViewer.IsDeferredScrollingEnabled="True"
ScrollViewer.CanContentScroll="False"
IsSynchronizedWithCurrentItem="True"
SelectionUnit="FullRow"
IsTabStop="True"
CanUserSortColumns="False"

AutoGenerateColumns="False" BorderThickness="0" ClipToBounds="True"
SnapsToDevicePixels="True" HeadersVisibility="None"
CanUserReorderColumns="False" CanUserResizeColumns="False"
SelectionMode="Single" PreviewKeyDown="objInnerDatagrid_PreviewKeyDown"
SelectionChanged="objInnerDatagrid_SelectionChanged">
<DataGrid.Columns>

<DataGridTextColumn Width="100" Binding="{Binding Model}"
CanUserSort="False" CanUserResize="False" CanUserReorder="False" />

<DataGridTextColumn Width="100" Binding="{Binding Year}"
CanUserSort="False" CanUserResize="False" CanUserReorder="False" />
</DataGrid.Columns>
<DataGrid.RowStyle>
<Style TargetType="{x:Type DataGridRow}">
<EventSetter Event="GotFocus" Handler="GotFocusRowDetails"/>
</Style>
</DataGrid.RowStyle>
</DataGrid>
</DataTemplate>
</DataGrid.RowDetailsTemplate>
<DataGrid.RowStyle>
<Style TargetType="{x:Type DataGridRow}">
<EventSetter Event="PreviewMouseLeftButtonDown" Handler="SelectRowDetails"/>
</Style>
</DataGrid.RowStyle>
<DataGrid.Columns>
<DataGridTextColumn Header="First Name" Width="100" Binding="{Binding FirstName}" IsReadOnly="False"/>
<DataGridTextColumn Header="Last Name" Width="100" Binding="{Binding LastName}" IsReadOnly="False"/>
</DataGrid.Columns>
</DataGrid>
<StackPanel Grid.Row="1" Orientation="Horizontal">

<Button VerticalAlignment="Center" x:Name="btnAddCar" Width="80"
Height="30" Content="Add Carr" Click="btnAddCar_Click" />

<Button Content="Delete Car" x:Name="btnDeleteCar" Width="80"
Height="30" VerticalAlignment="Center" HorizontalAlignment="Left"
Margin="20,0,0,0" Click="btnDeleteCar_Click" />

<Button Content="Delete Person" x:Name="btnDeletePerson" Width="80"
Margin="140,0,0,0" Height="30" Click="btnDeletePerson_Click"/>

<Button Content="Add Person" x:Name="btnAddPerson" Width="80"
Margin="20,0,0,0" Height="30" Click="btnAddPerson_Click" />
</StackPanel>
</Grid>
</Window>

C#-----------------------------------------------------------

using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
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 DataGridEx2
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
DataGrid _innerGrid;
private DataGrid _outerGrid = null;
ObservableCollection<Person> people;
public MainWindow()
{
InitializeComponent();
DataContext = this;
_innerGrid = this.FindName("objInnerDatagrid") as DataGrid;
_outerGrid = this.FindName("objDatagrid") as DataGrid;
people = CreateData();
_dataView = new ListCollectionView(people);
}
private ObservableCollection<Person> CreateData()
{
return new ObservableCollection<Person>()
{
new Person
{
FirstName = "Davide",
LastName = "Seddio",
Nationality="CH",
Cars = new ObservableCollection<Car>
{
new Car {Model = "Toyota", Year = 1977},
new Car {Model = "Mazda", Year = 1982}
}
},
new Person
{
FirstName = "Luca",
LastName = "Bianchi",
Nationality = "CH",
Cars = new ObservableCollection<Car>
{
new Car {Model = "Fiat", Year = 1977},
new Car {Model = "Ford", Year = 1982},
new Car {Model = "BMW", Year = 1980}
}
},
new Person
{
FirstName = "Marco",
LastName = "Milani",
Nationality = "CH",
Cars = new ObservableCollection<Car>
{
new Car {Model = "Suzuki", Year = 1977},
new Car {Model = "Subaru", Year = 1982}
}
},
new Person
{
FirstName = "Alfred",
LastName = "Zurcher",
Nationality = "CH",
Cars = new ObservableCollection<Car>
{
new Car {Model = "Mercedes", Year = 1977},
new Car {Model = "Ferrari", Year = 1982}
}
},
new Person
{
FirstName = "Franco",
LastName = "Veri",
Nationality = "IT",
Cars = new ObservableCollection<Car>
{
new Car {Model = "Audi", Year = 1977},
new Car {Model = "BMW", Year = 1982}
}
},
new Person
{
FirstName = "Luigi",
LastName = "Mulinelli",
Nationality = "IT",
Cars = new ObservableCollection<Car>
{
new Car {Model = "VW", Year = 1977},
new Car {Model = "Jaguar", Year = 1982}
}
},
new Person
{
FirstName = "Carlo",
LastName = "Zanfrini",
Nationality = "IT",
Cars = new ObservableCollection<Car>
{
new Car {Model = "Autobianchi", Year = 1977},
new Car {Model = "Lancia", Year = 1982}
}
},
new Person
{
FirstName = "Alex",
LastName = "Calderoli",
Nationality = "DE",
Cars = new ObservableCollection<Car>
{
new Car {Model = "Alfa Romeo", Year = 1977},
new Car {Model = "Renault", Year = 1982}
}
},
new Person
{
FirstName = "Andrea",
LastName = "Laranguate",
Nationality = "FR",
Cars = new ObservableCollection<Car>
{
new Car {Model = "Peugeot", Year = 1977},
new Car {Model = "Citroen", Year = 1982}
}
},
new Person
{
FirstName = "Oreste",
LastName = "Tranquilli",
Nationality = "EN",
Cars = new ObservableCollection<Car>()

//Cars = new ObservableCollection<Car>()
//{
// new Car {Model = "Saab", Year = 1977},
// new Car {Model = "Lamborghini", Year = 1982}
//}
}

};
}
private Person _selectedPerson;
public Person SelectedPerson
{
get { return _selectedPerson; }
set { _selectedPerson = value;
if(value != null)

Console.WriteLine("Selected Person = " + value.LastName+" Selected Car =
"+((SelectedCar !=null)?SelectedCar.Model:""));
}
}
private Car _selectedCar;
public Car SelectedCar
{
get { return _selectedCar; }
set
{

_selectedCar = value; if (value != null) Console.WriteLine("Selected
Car = " + value.Model+" Selected Person = "+((SelectedPerson

!=null)?SelectedPerson.LastName:""));
}
}
private ListCollectionView _dataView;
public ListCollectionView DataView
{
get { return _dataView; }
set { _dataView = value; }
}


private void objDatagrid_PreviewKeyDown(object sender, KeyEventArgs e)
{
Console.WriteLine("OUTER PreviewKeyDown");


//if (Keyboard.Modifiers == ModifierKeys.Shift && e.Key == Key.Tab)
//{
// DataGrid originalDataGrid = null;
// if (e.OriginalSource is DataGridCell)
// {
// originalDataGrid = VisualControlsAccess.GetDataGridFromCell((DataGridCell)e.OriginalSource);
// }
// if (originalDataGrid != null && !originalDataGrid.Name.Equals(_outerGrid.Name))
// {
// Console.WriteLine("Outer PreviewKeyDown selectedIndex" + originalDataGrid.SelectedIndex);
// ////originalDataGrid.MoveFocus(new TraversalRequest(FocusNavigationDirection.Previous));
// //DataGridRow row = VisualControlsAccess.GetDataGridRowFromCell((DataGridCell)e.OriginalSource);
// //row.Focus();
// }
// else
// _outerGrid.MoveFocus(new TraversalRequest(FocusNavigationDirection.Previous));
// e.Handled = true;
//}
//else if (Keyboard.Modifiers == ModifierKeys.None && e.Key == Key.Tab)
//{
// (Keyboard.FocusedElement as FrameworkElement).MoveFocus(new TraversalRequest(FocusNavigationDirection.Next));
// e.Handled = true;
//}
if (e.Key == Key.Down)
{
DataGrid grid = (DataGrid)e.Source;
if (grid.SelectedItem == null)
{
Console.WriteLine("1");
grid = (DataGrid)sender;
}
if (grid.SelectedItem is Person)
{
SelectedPerson = ((Person)grid.SelectedItem);
if (((Person)grid.SelectedItem).Cars.Count() > 0)
{
Console.WriteLine("2");
DataGridCellInfo selectedDataGridCellInfo = (grid.SelectedCells[0] as DataGridCellInfo?).Value;

DataGridRow rowContainer =
(DataGridRow)grid.ItemContainerGenerator.ContainerFromItem(selectedDataGridCellInfo.Item);
if (rowContainer != null)
{
Console.WriteLine("3");
DataGrid innerGrid = VisualControlsAccess.GetVisualChild<DataGrid>(rowContainer);
if (innerGrid != null)
{
Console.WriteLine("4");
if (innerGrid.Items != null && innerGrid.Items.Count > 0)
{
DataGridRow row = ((DataGridRow)innerGrid.ItemContainerGenerator.ContainerFromIndex(0));

DataGridCellsPresenter presenter =
VisualControlsAccess.GetVisualChild<DataGridCellsPresenter>(row);
if (presenter != null)
{
Console.WriteLine("5");

DataGridCell cell =
(System.Windows.Controls.DataGridCell)presenter.ItemContainerGenerator.ContainerFromIndex(0);
if (cell != null)
{
Console.WriteLine("6");
//row.MoveFocus(new TraversalRequest(FocusNavigationDirection.Next));
// Focus on the First Cell of the First InnerGrid Row
FocusManager.SetFocusedElement(innerGrid, cell as IInputElement);
innerGrid.SelectedIndex = 0;
row.Focus();
//FocusManager.SetIsFocusScope(cell, true);
//FocusManager.SetIsFocusScope(row, true);
//FocusManager.SetFocusedElement(innerGrid, row as IInputElement);
FocusManager.SetFocusedElement(innerGrid, row);
// Mark this event as handled.
e.Handled = true;
// Remove the selection from the outerGrid row.
this.Dispatcher.BeginInvoke((Action)(() =>
{
objDatagrid.SelectedIndex = -1;
}), null);
}
}
}

//DataGridCell cell = (System.Windows.Controls.DataGridCell)presenter
}

//DataGridCellsPresenter presenter =
VisualControlsAccess.GetVisualChild<DataGridCellsPresenter>(rowContainer);
//if (presenter != null)
//{

// DataGridCell cell =
(System.Windows.Controls.DataGridCell)presenter.ItemContainerGenerator.ContainerFromIndex(0);
//}
}
//e.Handled = true;
}
}
}
else if (e.Key == Key.Up)
{
DataGrid grid = (DataGrid)e.Source;
if (grid.SelectedItem is Person)
{
SelectedPerson = ((Person)grid.SelectedItem);
}
}
else if (e.Key == Key.Left || e.Key == Key.Right)
{
//Ignore Left and Right keys while in the DataGrid.
e.Handled = true;
}


}

private void objInnerDatagrid_PreviewKeyDown(object sender, KeyEventArgs e)
{
Console.WriteLine("INNER PreviewKeyDown");

if (e.Source is ItemsPresenter)
{
// Get the Selected Person from the DataContext.
SelectedPerson = ((Person)((ItemsPresenter)e.Source).DataContext);
}

}
//////////////////// PROBLEMS and FIXES //////////////////////
////// Mouse click focus on Inner row ////////////////////////
/// Fix, when the row selected is the outer Grid row, do nothing.
/// If the row selected is a inner grid row, the control tries to highlight both, inner and outer,
/// this will set the focus to the inner grid and remove focus from the outer grid.
private void SelectRowDetails(object sender, MouseButtonEventArgs e)
{

var rowSource = e.Source;
if (rowSource is DataGridCellsPresenter)
{
Console.WriteLine("SelectRowDetails 1");

}
else if (rowSource is DataGridDetailsPresenter)
{
Console.WriteLine("SelectRowDetails 2");
// Row selected is a Inner datagrid

DataGridRow row = sender as DataGridRow;
row.Focusable = true;
bool focused = row.Focus();

if (SelectedPerson == null)
{
// If first selection is an inner item, get the person from it.
SelectedPerson = (Person)row.Item;
}
// Gets the element with keyboard focus.
UIElement elementWithFocus = Keyboard.FocusedElement as UIElement;

// Change keyboard focus.
if (elementWithFocus != null)
{
elementWithFocus.MoveFocus(new TraversalRequest(FocusNavigationDirection.Next));
}
// Remove the focus from the outer row
this.Dispatcher.BeginInvoke((Action)(() =>
{
objDatagrid.SelectedIndex = -1;
}), null);
}
}
/// <summary>
/// Used to get the focused RowDetails
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void GotFocusRowDetails(object sender, RoutedEventArgs e)
{
SelectedCar = ((Car)((DataGridRow)sender).Item);
}
private void objDatagrid_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
//Console.WriteLine("OUTER SelectionChanged");
}


private void btnAddCar_Click(object sender, RoutedEventArgs e)
{
Person pers = (Person)_outerGrid.SelectedItem;

//Person pers = people.ToList().Find(p => p.FirstName.Equals("Oreste"));
if (pers != null)
{
pers.Cars.Add(new Car { Model = "Lamborghini", Year = 1982 });
}
}

private void btnDeleteCar_Click(object sender, RoutedEventArgs e)
{
var pers = _outerGrid.SelectedItem;
if (pers != null)
{
int indx = people.ToList().FindIndex(p => ((Person)p).FirstName.Equals(((Person)pers).FirstName));
if (indx >= 0)
{
people.RemoveAt(indx);
}
}
}

private void btnDeletePerson_Click(object sender, RoutedEventArgs e)
{
var pers = SelectedPerson;
if (pers != null)
{
int indx = people.ToList().FindIndex(p => ((Person)p).FirstName.Equals(((Person)pers).FirstName));
if (indx >= 0)
{
people.RemoveAt(indx);
}
}
}
int persNum = 0;
private void btnAddPerson_Click(object sender, RoutedEventArgs e)
{
people.Add(new Person
{
FirstName = "FirstName [ " + persNum + " ]",
LastName = "LastName [ " + persNum + " ]",
Nationality = "" + persNum,
Cars = new ObservableCollection<Car>
{
new Car {Model = "Car1 ["+persNum+" ]", Year = 1977},
new Car {Model = "Car2 ["+persNum+" ]", Year = 1982}
}
});
persNum++;
}

private void objInnerDatagrid_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
// Not needed, set in GetFocusRowDetails
//SelectedCar = (Car)((DataGrid)sender).SelectedItem;
}

}
public class Person
{
public string FirstName { get; set; }
public string LastName { get; set; }
public string Nationality { get; set; }
public ObservableCollection<Car> Cars { get; set; }
}
public class Car
{
public string Model { get; set; }
public int Year { get; set; }
}
}

how to convert UI element into Drawing Brush

$
0
0

Hi all,

how can i convert UI element into Drawing Brush,

for eg : in Expression Blend

<Canvas>

<Button Content="Sample Button">

</Button>

</Canvas>

in Expression Blend i can directly create the canvas as Drawing Brush

1)Selecting the Canvas from Objects and TimeLine tab

2) Click on Tools Menu

3) Click on Make Brush Resource

4) Click on Make Drawing Brush Resource

But i want to do this thing from code behind... how can i achieve this functionality .. can any one help me on this..

--

SharathKumar11



sharathkumar11

Auto Complate Textbox

$
0
0

hi 

how can i create auto complate textbox ?

Dynamicaly change binding based on language

$
0
0

Hello

I have TextBox. I have one class object.

Public Class MyClass

{

   public string engData{get; set;}

   public string japData{get; set;}

}

Now I want to change binding of text ptoperty to the columns based onlanguage.

Like If current language is english then textbox's text property should be binded twoway with engData .

If current language is changed to japanese then text property should binded to japData.

I am following MVVM so i can not write on button click.

So is there any general way to do it?

Regards

Viewing all 18858 articles
Browse latest View live


<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>