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

Focus issue of Custom Control like ComBox using as a Editor in DataGrid.

$
0
0

I have designed an User Defined control like ComboBox using ToggleButton and Popup.

Now I am trying to use this control in CellEditingTemplate of DataGrid. And it is working fine. But issues is that when I try to edit the cell, it shows that control, it opens the Popup (Popup contains DataGrid, ToolBar etc.). When I try to click on any Control within the Popup, focus goes to DataGridCell. That's why I am unable to click any ToolBar Button or unable to select any cell of DataGrid. Now how can I stop this.


Cannot await System.Collections

$
0
0

        public async Task <List<modeloCredito>> GetCreditos(string Cliente) 
        {
            manCredito manCre = new manCredito();
            try
            {
                //Here i hava my problem cant await this function

                IEnumerable<modeloCredito> ecredito = await manCre.getCredito(Cliente);
                return ecredito.ToList();

            }
            catch (Exception ex) 
            {
                string Error = ex.Message.ToString();
                return null;
            }
        }

         public async Task <IEnumerable<modeloCredito>> getCredito(string ClaveCliente)
        {
            try
            {
               
                List<clsParametros> Lista = new List<clsParametros>();
                Lista.Add(new clsParametros("@ClaveCliente",ClaveCliente));

                DataTable Datos =  await AccesoDB.Standart("sp_GetCredito", Lista);

                return Datos.AsEnumerable().Select(row => 
                {
                    return new modeloCredito 
                    {
                        IdCredito = Convert.ToInt32(row["IdCredito"]),
                        NumeroCredito = Convert.ToInt32(row["NumeroCredito"]),
                        NumeroCliente = Convert.ToInt32(row["ClaveCliente"]),
                        NombreCliente = (row["NombreCliente"]).ToString(),
                        Tipo = (row["Tipo"]).ToString(),
                        Saldo = Convert.ToDecimal(row["Saldo"]),
                        Total = Convert.ToDecimal(row["Total"]),
                        TipoCredito = (row["TipoCredito"]).ToString(),
                        Fecha = Convert.ToDateTime(row["Fecha"])
                    };
                });
            }
            catch (Exception ex)
            {
                string Error = ex.Message.ToString();
                return null;
            }
        }


                

Slow program startup

$
0
0

I am struggling with program load time due to querying (LinqToEntities) a database at start up. Thanks to WPF: Dynamic XAML - Awkward Data I have been able to build the datagrid the way I need to.


At startup the queries retrieve the planning calendar for around 80 items over 2 weeks. The more missions there are the longer it takes to load. I have tried to reduce code below to a minimum

namespace BuildDataGrid
{
    class CalendarViewModel : ModelBase
    {
        public ObservableCollection<CalendarItem> CalendarItems { get; set; }

        List<Mission> currentMissions = new List<Mission>(); // to store current mission data
        List<CurrentMissionData> missionData = new List<CurrentMissionData>();

        public CalendarViewModel()
        {
            // get the list of current missions from selected dates (default 14 day period) with helper method
            // getting the list of missions here I hope to reduce processor time when quering items in all missions.
            // The program will only query selected missions when looking for freight and missions dates for an item
            currentMissions = HelperMethods.GetMissionsInDateRange(Variables.calendarStart, Variables.calendarEnd);

            CalendarItems = new ObservableCollection<CalendarItem>();

            using (MaterialEntities me = new MaterialEntities())
            {
                // get the items data for the selected category
                var itemList = from i in me.items
                               where !i.isReturned
                               where i.Category.categoryID == 1 // laptop category (81 laptops)
                               orderby i.name
                               select new CalendarItem
                               {
                                   ID = i.itemID,
                                   Name = i.name,
                                   Model = i.model,
                                   Type = i.Type.typeName,
                                   Category = i.Category.categoryName,
                                   Status = i.Status.currentStatus,
                                   Note = i.note,
                               };

                // Fill the OClist with items from the category selected by the user
                foreach (CalendarItem cal in itemList)
                {
                    // get the missions data for each item as the method cannot be called in a linq select clause
                    List<CurrentMissionData> itemMissionDateData = new List<CurrentMissionData>();
                    if (currentMissions != null) // no need to process any items if there are no missions
                    {
                        for (DateTime dt = Variables.calendarStart; dt < Variables.calendarEnd; dt = dt.AddDays(1))
                        {
                            var result = (from m in currentMissions
                                          join link in me.LinkMissionItems on m.MissionID equals link.missionID
                                          where dt <= m.freightReturn && dt >= m.freightLeave
                                          where link.itemID == cal.ID
                                          select new CurrentMissionData
                                          {
                                              ItemID = link.itemID,
                                              MissionID = m.MissionID,
                                              MissionName = link.Mission.MissionName,
                                              MissionNumber = link.Mission.MissionNo,
                                              FL = m.freightLeave,
                                              FR = m.freightReturn,
                                              MS = m.missionStart,
                                              ME = m.missionEnd
                                          }).FirstOrDefault();

                            if (result != null) // set the cell background colour. In transit TAN, in mission ORANGE
                            {
                                if ((dt.Date >= result.FL && dt.Date < result.MS) || (dt.Date > result.ME && dt.Date <= result.FR))
                                {
                                    result.CellBackground = "Tan";
                                }
                                else
                                {
                                    result.CellBackground = "Orange";
                                }
                            }

                            itemMissionDateData.Add(result); // add to missions data list

                        } // for (DateTime dt = Variables.calendarStart;..................
                    }

                    cal.MissionDates = itemMissionDateData; // add mission data list to Calendar item
                    CalendarItems.Add(cal); // update the calendar items list

                } // foreach (CalendarItem cal in itemList)

            } // using (MaterialEntities me = new MaterialEntities())

        } // CalendarViewModel()

    } // class CalendarViewModel
} // namespace BuildDataGrid


It is the looping through the cells that takes the time. Having never used threads before, I am not sure this would help as the program fills cell by cell so is not a separate process. 


:-( Still trying to program

Speedup Getting Data

$
0
0

Hi

I'm using VS 2013, EF6, WPF

I have 2 project once WPF and other is MVC, both Application using a MSSQL Server 2008 databace that is in my shared host server.

my MVC application work well but WPF application getting 3 to 5 second to receive data from database.

I need to know is there some trick or method to speedup the proses?

if you know the answer please also let me know where can I get started to learn about it.

thanks  

DataGrid and Sum

$
0
0

my xaml code;

<DataGridTextColumn Width="*" Header="Toplam Ödenen" Binding="{Binding Toplam ODENEN, StringFormat=\{0:C2\}}" d:IsLocked="True"><DataGridTextColumn.CellStyle><Style TargetType="{x:Type DataGridCell}"><Setter Property="Background" Value="#A2D1A2" /><Setter Property="HorizontalAlignment" Value="Stretch" /></Style></DataGridTextColumn.CellStyle><DataGridTextColumn.ElementStyle><Style TargetType="{x:Type TextBlock}"><Setter Property="TextAlignment" Value="Center" /></Style></DataGridTextColumn.ElementStyle></DataGridTextColumn>

mycode;

var TotalSum = GenelOdemeTablosu.ItemsSource.Cast<DataRowView>().Sum(rowSum => (decimal)rowSum["Toplam Ödenen"]);

How do I make the TotalSum;

thanks;



VS 2015 vshost32.exe crash when quitting WPF 4.0 application.

$
0
0

Windows Forms, Windows Store, Console applications are fine.

WPF 3.0 applications are fine.

When debugging WPF 4.0 or above application, quitting the application by clicking the [X] shows 

vshost32.exe has stopped working
Problem Event Name:	BEX
  Application Name:	WpfApplication7.vshost.exe
  Application Version:	14.0.22512.0
  Application Timestamp:	54b37968
  Fault Module Name:	ntdll.dll
  Fault Module Version:	6.3.9600.17476
  Fault Module Timestamp:	54516af9
  Exception Offset:	000f4e24
  Exception Code:	c000000d
  Exception Data:	00000000
  OS Version:	6.3.9600.2.0.0.256.4
  Locale ID:	1033
  Additional Information 1:	ea79
  Additional Information 2:	ea798abdedba1e36c19f871efd491e30
  Additional Information 3:	bffa
  Additional Information 4:	bffab8226803735d5a18ddfce34aafa1

This is not caused by my code, because it happens with the template project (created a new WPF application and not modified anything).

I tried Repair and I tried uninstalling everything (I mean everything seemed to be related in the Add or Remove applications) and reinstalled VS 2015. The problem persists.

CTP 14.0.225120.DP


WPF 4.5 doesn’t show the option to open the project in Blend for Visual Studio 2013

$
0
0

Hi,

In my WPF 4.5 project in Visual Studio 2013, when I right clicked the name of my project it doesn’t show the option to open in Blend for Visual Studio 2013….. and when I try to open the project with Blend for Visual Studio 2013, it doesn't show anything..... I don't see the project nor the UI of my WPF 4.5 project

How I can open my project in Blend for Visual Studio 2013???

Thanks!!!

Regards,

How to bind a Style Control element to another Control?

$
0
0

I have this custom slider:

<Style x:Key="MySlider" TargetType="{x:Type Slider}"><Setter Property="Template"><Setter.Value><ControlTemplate TargetType="{x:Type Slider}"><Border Background="{TemplateBinding Background}" BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}"><Grid><Grid.RowDefinitions><RowDefinition Height="Auto"/><RowDefinition Height="Auto" MinHeight="{TemplateBinding MinHeight}"/><RowDefinition Height="Auto"/></Grid.RowDefinitions><TickBar x:Name="TopTick" Visibility="Visible" Fill="{TemplateBinding Foreground}" Placement="Top" Height="4" Grid.Row="0"/><local:CustomTickBar Name="BottomTick" Margin="5,0,10,0" SnapsToDevicePixels="True" Grid.Row="0"
                                       Fill="{TemplateBinding Foreground}" Placement="Top" Height="4" Visibility="Visible"/><Border x:Name="TrackBackground"
 BorderThickness="1" CornerRadius="1"
 Margin="5,0" VerticalAlignment="Center" Height="4.0" Grid.Row="1" ><Canvas Margin="-6,-1"><Rectangle Visibility="Hidden" x:Name="PART_SelectionRange" Height="4.0"
 Fill="{DynamicResource {x:Static SystemColors.HighlightBrushKey}}"
 Stroke="{DynamicResource {x:Static SystemColors.ControlDarkDarkBrushKey}}"
 StrokeThickness="1.0"/></Canvas></Border><Track x:Name="PART_Track" Grid.Row="1"><Track.DecreaseRepeatButton><RepeatButton x:Name="Dimi" Visibility="Visible" Command="{x:Static Slider.DecreaseLarge}"></RepeatButton></Track.DecreaseRepeatButton><Track.IncreaseRepeatButton><RepeatButton Command="{x:Static Slider.IncreaseLarge}"/></Track.IncreaseRepeatButton><Track.Thumb><Thumb x:Name="Seta" Style="{StaticResource CustomThumbForSlider}" Background="Black"/></Track.Thumb></Track></Grid></Border></ControlTemplate></Setter.Value></Setter></Style>


And a RichTextBox where I want to bind Paragraph Indent to  the slider decrease button actualwidth. Tried:

<RichTextBox x:Name="rtb1" Margin="267,25,80,326" BorderBrush="Gray" Padding="0"

							local:RichTextBoxHelper.DocumentXaml ="{Binding SelectedItem.Texto, ElementName=datagrid1}"
							ScrollViewer.VerticalScrollBarVisibility="Auto" SelectionChanged="rtb1_SelectionChanged"
							HorizontalContentAlignment="Left" VerticalContentAlignment="Stretch"
                                     IsDocumentEnabled="True" Grid.Column="1" UseLayoutRounding="False"
                                     BorderThickness="0" SnapsToDevicePixels="True" Grid.Row="1"
                                     Grid.IsSharedSizeScope="True" ClipToBounds="True" IsManipulationEnabled="True"><FlowDocument><Paragraph TextIndent="{Binding ElementName=Dimi, Path=ActualWidth}"></Paragraph></FlowDocument></RichTextBox>

But did not work. My custom decrease button called "Dimi" does not appear even in the autocomplete after writing ElementName= ...

Can anyone help me please?


How to create a "Pressed" effect for WPF Button?

$
0
0

Hi,

I've been searching for quite sometime but I'm not able to find a way to give a "Pressed" effect to a button when it is clicked, a la "Popup" style in C#.

Could someone help me in this regard?

Currently I'm using the following code for setting up a circular button.

<Button x:Name="btnNew" Content="Delivery Note" HorizontalAlignment="Left" Margin="512,147,0,0" VerticalAlignment="Top" Width="63" Height="63" BorderThickness="0" Click="Button_Click_1" Cursor="Hand" Padding="1,1,1,1" UseLayoutRounding="True" >
            <Button.Effect>
                <DropShadowEffect ShadowDepth="2" />
            </Button.Effect>
            <Button.Template>
                <ControlTemplate TargetType="Button">
                    <Grid>
                        <Ellipse Stroke="Black">
                            <Ellipse.Fill>
                                <ImageBrush ImageSource="Images/Delivery.png">
                                </ImageBrush>
                            </Ellipse.Fill>
                        </Ellipse>
                    </Grid>
                </ControlTemplate>
            </Button.Template>
        </Button>

Thanks


Strange x:Static binding bug

$
0
0

I have found a rather odd bug with using x:Static binding in WPF.

I created a static class with static properties and then tried to bind to it, it worked in one window but not in another window, eventually I boiled down the problem to the order of the xmlns in the window xaml

Here is a set of sample code that should work

RedBlue.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace abc.WPFBugTest
{
    public static class RedBlue
    {
        public static string ReleaseDebugTextDisplay { get { return " - = ReleaseDebugTextDisplay = - "; } set { } }
        public static string DebugReleaseStringValue { get { return " - = DebugReleaseStringValue = - "; } set { } }
        public static string BlingBlong { get { return " - = BlingBlong = - "; } set { } }
        public static string Value1 { get { return " - = Value 1 = - "; } }
        public static string Value2 { get { return " - = Value 2 = - "; } set { } }
        public static string Value3 { get { return " - = Value 3 = - "; } }
    }
}


MainWindow.xaml

<Window x:Class="abc.WPFBugTest.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:local="clr-namespace:abc.WPFBugTest;assembly=abc.WPFBugTest"
        xmlns:local2="clr-namespace:abc.WPFBugTest"

        Title="RecordersDialog" ShowInTaskbar="False" Topmost="True"
        Left="200" Top="200"  SizeToContent="WidthAndHeight" ResizeMode = "NoResize" ><Label HorizontalAlignment="Center" VerticalAlignment="Bottom" FontSize="26" Grid.Column="1" Content="{x:Static local:RedBlue.Value2}"><Label.Effect><DropShadowEffect Color="NavajoWhite" ShadowDepth="0" Direction="90" Opacity="1" BlurRadius="5"/></Label.Effect></Label></Window>

The bug can be invoked by changing the xmlns:local2 value to xmlns:local2="clr-namespace:abc.WPFBugTest;assembly=abc.WPFBugTest" or by removing xmlns:local2 value.

However if the xmlns:local2 is removed and the xmlns:local value is moved above the xmlns:x value that fixes the problem.

The error I get says "Cannot find the type 'RedBlue'. Note that type names are case sensitive."

I am using this version of Visual Studio
Microsoft Visual Studio Professional 2013
Version 12.0.30501.00 Update 2
Microsoft .NET Framework
Version 4.5.50938


Am I doing the binding wrong or is there some sort of bug with Visual Studio itself?

Binding to Loaded XAML File

$
0
0

I have a project that saves a canvas containing numerous UI Controls.  However when I load the canvas again all of the controls are present with the correct values. But all of the Bindings to the control properties are no longer updated when the source changes. Why is this ?. Whats missing. I tried Resetting the dataContext and many other things that People have suggest but with no success. I don't have enough experience with WPF to fully understand yet what has gone wrong.

Open and save code taken from (http://www.codeproject.com/Articles/24681/WPF-Diagram-Designer-Part)

the Controls are contained in a separate Control library


Developer of bits

Custom UIElement

$
0
0

Hi,

I have a custom Node:UIElement and a custom view class which contains a collection of Nodes.

When I try to add Nodes in XAML, they don't show up, even though when I step through I can see they exist in the HattenView's collection.  If I add a button control to the XAML inside the view, it shows up.

I've been looking at this for so long now and just can't seem to figure out why these notes aren't showing.

 <Grid Name="HattenContentGrid" >

            <MyPresentation:HattenView x:Name="GSM"  >


            <MyPresentation:HattenView.Nodes>

                        <MyPresentation:Node Name="UNREG2G" Bounds="20,35,150,80"  Text="UNREGISTERED" TextAlignment="Center" ClipToBounds="True"

                          TextBrush="LavenderBlush" FontSize="15" Shape="RoundRect" Opacity="0.0" Image="{StaticResource UNREG2G}" ImageAlign="Fit" />

using System;

using System.Collections;

using System.Collections.Generic;

using System.Windows;

using System.Windows.Controls;

using System.Windows.Media;

using System.Windows.Shapes;

using Logic.Itsa;


namespace Presentation.MyPresentation

{

    public class HattenNodeCollection

    {

        private List<Node> _nodes;

        public List<Node> Nodes

        {

            get { return _nodes; }

            set { _nodes = value; }

        }

    }


    public class Node : UIElement

    {

        public HattenView HattenView { get; set; }

        public string Name { get; set; }

        public string Tag { get; set; }

        public string Text { get; set; }

        public int StrokeThickness { get; set; }

        public bool Visible { get; set; }

        public Rect Bounds { get; set; }

        public Brush TextBrush { get; set; }

        public Brush Brush { get; set; }

        public string Shape { get; set; }

        public DrawingImage Image { get; set; }

        public ImageAlign ImageAlign { get; set; }

        public TextAlignment TextAlignment { get; set; }

        public Double FontSize { get; set; }

        public HattenNodeVisual VisualObject { get; set; }

        //public HattenNodeVisual.HandlesStyle HandlesStyle { get; set; }

        public Brush Stroke

        {

            get;

            set;

        }

        //public void ZBottom()

        //{

        //    if (HattenView != null)

        //    {

        //        HattenView.ZBottom(this);

        //        Repaint();

        //    }

        //}

        protected void Repaint()

        {

            //    //if (diagram != null && !diagram.NowLoading)

            //    //    diagram.Invalidate(GetRepaintRect(false));

            //    Repaint(false);

        }


        ///// <summary>

        ///// Repaints the specified region of the diagram.

        ///// </summary>

        //public virtual void Repaint(bool includeConnected)

        //{

        //    if (diagram != null && !diagram.NowLoading)

        //        diagram.Invalidate(invalidRect);

        //    Utilities.InvalidateVisual(this);

        //    if (UIElement != this)

        //        Utilities.InvalidateVisual(UIElement);

        //    Utilities.InvalidateVisual(adorner);


        //     include the group objects rectangles in the update area

        //    if (includeConnected && subordinateGroup != null)

        //        subordinateGroup.Repaint();

        //}

        public void Render(DrawingContext dc) { OnRender(dc);}

        protected override void OnRender(DrawingContext dc)

        {

            dc.DrawImage(this.Image, this.Bounds);

            dc.DrawRectangle(null, null, Bounds);


        }

    }


    public class NodeAdapter : Node

    {

       

    }

}

        protected override void OnRender(DrawingContext drawingContext)

        {

            //double x = 0, y = 0;

            foreach (Node n in Nodes)

            {

                n.Render(drawingContext);

                n.MouseEnter += UIElement_OnMouseEnter;


            }

        }

Codeproject Modern UI how to go to another page from another link

$
0
0

 am currently using Modern UI from CodePlex. It is great and easy to use but there are some classes and events that I am not familiar with. Example: I have two GroupLinks named "Patients" and "Configurations". There are several pages in each of the GroupLinks. I tried to navigate from one page to another using a button click event. It worked. But when I tried navigating from Page1 of GroupLink2 to Page1 of GroupLink1, it still worked, but the problem was the active GroupLink remained in GroupLink2 instead of GroupLink1 just like the screenshots show below:

GroupLink2

GroupLink2 but the page is from GroupLink1

Btw, I used the code behind to navigate from Allergies(IrritantPage) to PatientsPage:

privatevoidFilterControl_OnToPatientClick(object sender,RoutedEventArgs e){NavigationCommands.GoToPage.Execute("/MainContents/PatientGridPage.xaml",this);}

So how do I solve this? What event shall I use to make GroupLink1 the active GroupLink?

Also, whenever I compile the project, the default active GroupLink is always GroupLink2, how do I set the active GroupLink into GroupLink1 whenever I first ran the project?

Make control unaffected to ClipToBounds

$
0
0

Hi everyone,

I'm now making my own Metro ToggleSwitch control base on the original button.
I want it to be like this :

The yellow area is a border which I set ClipToBounds to true and the RED thumb is an element which is contained inside the yellow border. But what I've got is :

My question is : How can I make my Red thumb be unaffected to ClipToBounds of the Yellow border ?

Thank you :)

WPF TextBox Keep Selection

$
0
0

Programs like Notepad and Notepad++ have this feature where when you want to find words, you bring up the Find menu and enter your query and start searching. The interesting part in this is that when you're searching for the words, the find window doesn't loose focus and the user can use the 'ENTER' key to keep scrolling through all the words. The end result is that the text is selected and highlighted and still has the focus on the window. 

For me, I've got a Find form and I'm trying to do exactly hat Notepad does when it finds words. It shouldn't loose focus on the find window so the user can keep hitting the 'ENTER' key while going through the textbox for words. I can't seem to get this to work mainly because I'm using Textbox.Select(start, end) and right after that TextBox.Focus. This is the only way I can select Text in the TextBox. To open the Form I make it an owner form through the Main form.

Is it possible to do what Notepad is doing in terms of highlighting the text without loosing the focus on the form without needing to rewrite a Custom TextBox? I don't intend to use a RichTextBox and I'm aware of the IsInactiveSelectionHighlightEnabled.


MessageBox.Show("Hey You!")


How to to slect opened window on specific monitor in multi monitor system

$
0
0

Hi,

I have four monitor attached to my box. I have already implemented code to move selected window on given monitor on hokey. e.g window1 is opened on monitor one and if that window is active then using hot key i am moving it to specified monitor like Ctrl+1 move to monitor 1, Ctrl + 2 move to monitor 2 ..so on..

Now i want to implement another hot key, which will activate the window opened on specified monitor. means if i press Alt +1 then if any window is on the monitor should get active and if i press alt + 3 then if any window is there on monitor 3 should get activated.So how to achieve this?

H


Vipul Mistry Sr. Embedded Engineer www.eInfochips.com

How to binding and change VM property value when DataTrigger?

$
0
0

Hi all,

Please see the below code. The current work is when mouse over myButton then set textbox value as 3. Then binding this value to ViewModel property, at this time, the new value of ViewModel property also be 3.

The textbox just like a bridge. Can I remove this bridge and change the VM property directly when <setter..... in myTrigger style? thanks.

<Style x:Key="myTrigger" TargetType="TextBox"><Style.Triggers><DataTrigger Binding="{Binding IsMouseOver, ElementName=myButton}" Value="True"><Setter Property="Text" Value="3"></Setter></DataTrigger></Style.Triggers></Style>

WPF+MAF - addin referenced libraries are not loaded?

$
0
0

Hi! I'm new to Add-in framework. Now I'm trying to create WPF addin that returns UserControl (according to https://msdn.microsoft.com/en-us/library/bb909849(v=vs.110).aspx).

The problem is that when I try to get user control from addin, Exceptions are thrown:

1. The first exception was "Cannot find resource named '<name>'. Resource names are case sensitive.". All the resources are stored in separate library and it worked fine when I did the same with MEF (before MAF)

2. OK, I've removed all StaticResources and then I got another exception: "{"Could not load file or assembly 'Infralution.Localization.Wpf, PublicKeyToken=547ccae517a004b5' or one of its dependencies."}". This lib is used for localization.

Note: all needed libraries are in the same folder as the addin is

Are addin referenced libraries not loaded? Or where was I mistaken? 

Binding resource to a string property in view model!

$
0
0

Hi Everyone,

In my project I a build a ResourceDictionary on the fly which contains language translation stuff. For a given key it returns me the value (depending on current set language).

For example if the language I set is English then the ResourceDictionary contains:

<Node Key=Name>

Name

</Node>

Now I have bound this to XAML view correctly using dynamic property like:

Content="{DynamicResource Name}"

and in code behind, in some cases where I build the menu on the fly, I have this in view model:

 var myMenu= new MyMenuItem
            {
               ...
                Header = Application.Current.GetResource("Name"),
               ...
            };

which works fine.

But as you can see the problem is that I have to execute this piece of code in the view model every time I change the language. So I am using a LanguageChange event which triggers this piece of code.

I want to remove this event and make it work just like it work in the XAML. 

So is there anyway I can just execute the code above once, and every time the language changes the values are reflected everywhere. I think I can turn all such strings in ViewModel to DependencyProperty and then bind them to the resource in the code behind, but there are just too many of them so I am looking for a quicker way.

Thanks.


Please Mark as Answered If this answers your question OrUnMark as Answered if it did not.
Happy to Help :)
My Site


Passing parameter to Constructor in XAML

$
0
0

How can I pass parameters to a constructor in XAML.

I implemented a attached property, but this only get updated if the source will change :)

Viewing all 18858 articles
Browse latest View live


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