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

DataTemplate for class defined in another assembly not loading

$
0
0

A little background, I am working on a client server application using MVVM.

I have a common assembly that contains the models.

In my client solution I have a WPF Controls library that defines a data templates for the models in the common assembly.

The client application references the WPF controls library. When I run the application the data templates are not found.

I did some researching in reference source and found that Content Presenter will attempt to find the Data Template using a DataTemplateKey. The problem here is that DataTemplateKey use  the data type's (Model in the common assembly) assembly in its implementation of Resource Key.


NullReferenceException in Window.Show

$
0
0

Hi,

when starting-up my WPF application a splash screen in a separate thread is shown. Calling 'splash.Show()' (see code below) sometimes causes a NullReferenceException (see stack trace below). This NRE exception appears right after reboot of windows machine, at the first attempt to start the WPF application. All following application start-ups are successful.

The splash screen window is defined by Xaml using MVVM pattern.

Can anybody explain this behavior? Is this a Binding problem?

Code running in separate thread:

        public static void RunSplashScreenInSeparateThread()
        {
            var splash = new MarsSplashScreen();
            mSplashIsOn = true;
            splash.Show();
            splash.SetUpProgress(0, 20);
            mSplashScreen = splash;
            mSplashDispatcher = splash.Dispatcher;
            splash.Closed += (sender2, e2) => splash.Dispatcher.InvokeShutdown();
            if (!mSplashIsClosed) // check whether bootstrapper start-up succeeded. If not, dispatcher shall not run
                Dispatcher.Run();
        }

Stacktrace of NRE:

2013-08-16 15:43:17.3750 | ERROR | (8) | MarsApplication | Object reference not set to an instance of an object. | System.NullReferenceException: Object reference not set to an instance of an object.
   at MS.Internal.AssemblyHelper.IsXLinqCollectionPropertyImpl(PropertyDescriptor pd)
   at MS.Internal.AssemblyHelper.IsXLinqCollectionProperty(PropertyDescriptor pd)
   at MS.Internal.Data.ValueTable.ShouldCache(Object item, PropertyDescriptor pd)
   at MS.Internal.Data.DataBindEngine.RegisterForCacheChanges(Object item, Object descriptor)
   at MS.Internal.Data.PropertyPathWorker.ReplaceItem(Int32 k, Object newO, Object parent)
   at MS.Internal.Data.PropertyPathWorker.UpdateSourceValueState(Int32 k, ICollectionView collectionView, Object newValue, Boolean isASubPropertyChange)
   at MS.Internal.Data.ClrBindingWorker.AttachDataItem()
   at System.Windows.Data.BindingExpression.Activate(Object item)
   at System.Windows.Data.BindingExpression.AttachToContext(AttachAttempt attempt)
   at System.Windows.Data.BindingExpression.AttachOverride(DependencyObject target, DependencyProperty dp)
   at System.Windows.Data.BindingExpressionBase.Attach(DependencyObject target, DependencyProperty dp)
   at System.Windows.Data.BindingExpressionBase.OnAttach(DependencyObject d, DependencyProperty dp)
   at System.Windows.StyleHelper.GetInstanceValue(UncommonField`1 dataField, DependencyObject container, FrameworkElement feChild, FrameworkContentElement fceChild, Int32 childIndex, DependencyProperty dp, Int32 i, EffectiveValueEntry& entry)
   at System.Windows.StyleHelper.GetChildValueHelper(UncommonField`1 dataField, ItemStructList`1& valueLookupList, DependencyProperty dp, DependencyObject container, FrameworkObject child, Int32 childIndex, Boolean styleLookup, EffectiveValueEntry& entry, ValueLookupType& sourceType, FrameworkElementFactory templateRoot)
   at System.Windows.StyleHelper.GetChildValue(UncommonField`1 dataField, DependencyObject container, Int32 childIndex, FrameworkObject child, DependencyProperty dp, FrugalStructList`1& childRecordFromChildIndex, EffectiveValueEntry& entry, ValueLookupType& sourceType, FrameworkElementFactory templateRoot)
   at System.Windows.StyleHelper.GetValueFromTemplatedParent(DependencyObject container, Int32 childIndex, FrameworkObject child, DependencyProperty dp, FrugalStructList`1& childRecordFromChildIndex, FrameworkElementFactory templateRoot, EffectiveValueEntry& entry)
   at System.Windows.StyleHelper.ApplyTemplatedParentValue(DependencyObject container, FrameworkObject child, Int32 childIndex, FrugalStructList`1& childRecordFromChildIndex, DependencyProperty dp, FrameworkElementFactory templateRoot)
   at System.Windows.StyleHelper.InvalidatePropertiesOnTemplateNode(DependencyObject container, FrameworkObject child, Int32 childIndex, FrugalStructList`1& childRecordFromChildIndex, Boolean isDetach, FrameworkElementFactory templateRoot)
   at System.Windows.FrameworkTemplate.InvalidatePropertiesOnTemplate(DependencyObject container, Object currentObject)
   at System.Windows.FrameworkTemplate.HandleBeforeProperties(Object createdObject, DependencyObject& rootObject, DependencyObject container, FrameworkElement feContainer, INameScope nameScope)
   at System.Windows.FrameworkTemplate.<>c__DisplayClass6.<LoadOptimizedTemplateContent>b__3(Object sender, XamlObjectEventArgs args)
   at System.Xaml.XamlObjectWriter.OnBeforeProperties(Object value)
   at System.Xaml.XamlObjectWriter.Logic_CreateAndAssignToParentStart(ObjectWriterContext ctx)
   at System.Xaml.XamlObjectWriter.WriteStartMember(XamlMember property)
   at System.Xaml.XamlWriter.WriteNode(XamlReader reader)
   at System.Windows.FrameworkTemplate.LoadTemplateXaml(XamlReader templateReader, XamlObjectWriter currentWriter)
   at System.Windows.FrameworkTemplate.LoadTemplateXaml(XamlObjectWriter objectWriter)
   at System.Windows.FrameworkTemplate.LoadOptimizedTemplateContent(DependencyObject container, IComponentConnector componentConnector, IStyleConnector styleConnector, List`1 affectedChildren, UncommonField`1 templatedNonFeChildrenField)
   at System.Windows.FrameworkTemplate.LoadContent(DependencyObject container, List`1 affectedChildren)
   at System.Windows.StyleHelper.ApplyTemplateContent(UncommonField`1 dataField, DependencyObject container, FrameworkElementFactory templateRoot, Int32 lastChildIndex, HybridDictionary childIndexFromChildID, FrameworkTemplate frameworkTemplate)
   at System.Windows.FrameworkTemplate.ApplyTemplateContent(UncommonField`1 templateDataField, FrameworkElement container)
   at System.Windows.FrameworkElement.ApplyTemplate()
   at System.Windows.FrameworkElement.MeasureCore(Size availableSize)
   at System.Windows.UIElement.Measure(Size availableSize)
   at System.Windows.Controls.GridViewRowPresenter.MeasureOverride(Size constraint)
   at System.Windows.FrameworkElement.MeasureCore(Size availableSize)
   at System.Windows.UIElement.Measure(Size availableSize)
   at System.Windows.Controls.Border.MeasureOverride(Size constraint)
   at System.Windows.FrameworkElement.MeasureCore(Size availableSize)
   at System.Windows.UIElement.Measure(Size availableSize)
   at System.Windows.Controls.Control.MeasureOverride(Size constraint)
   at System.Windows.FrameworkElement.MeasureCore(Size availableSize)
   at System.Windows.UIElement.Measure(Size availableSize)
   at System.Windows.Controls.VirtualizingStackPanel.MeasureOverride(Size constraint)
   at System.Windows.FrameworkElement.MeasureCore(Size availableSize)
   at System.Windows.UIElement.Measure(Size availableSize)
   at System.Windows.ContextLayoutManager.UpdateLayout()
   at System.Windows.UIElement.UpdateLayout()
   at System.Windows.Interop.HwndSource.SetLayoutSize()
   at System.Windows.Interop.HwndSource.set_RootVisualInternal(Visual value)
   at System.Windows.Interop.HwndSource.set_RootVisual(Visual value)
   at System.Windows.Window.SetRootVisual()
   at System.Windows.Window.SetRootVisualAndUpdateSTC()
   at System.Windows.Window.SetupInitialState(Double requestedTop, Double requestedLeft, Double requestedWidth, Double requestedHeight)
   at System.Windows.Window.CreateSourceWindow(Boolean duringShow)
   at System.Windows.Window.CreateSourceWindowDuringShow()
   at System.Windows.Window.SafeCreateWindowDuringShow()
   at System.Windows.Window.ShowHelper(Object booleanBox)
   at System.Windows.Window.Show()
   at RohdeSchwarz.API.Bootstrapper.Graphical.DynamicSplashScreen.RunSplashScreenInSeparateThread()
   at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
   at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean ignoreSyncCtx)
   at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
   at System.Threading.ThreadHelper.ThreadStart()

Xaml of splash screen (The image in this Xaml is of type 'svg' and it is not posted due to confidential matter):

<GraphicalShell:DynamicSplashScreen x:Class="RohdeSchwarz.API.Bootstrapper.Graphical.MarsSplashScreen"
                                    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                                    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
                                    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
                                    xmlns:d="http://schemas.microsoft.com/expression/blend/2008" mc:Ignorable="d"
                                    xmlns:svg="http://sharpvectors.codeplex.com/runtime/"
                                    xmlns:GraphicalShell="clr-namespace:RohdeSchwarz.API.Bootstrapper.Graphical" x:Name="MarsSplashScreenControl"
                                    Width="640" Height="480" Background="White">

  <Border BorderBrush="Black" BorderThickness="1">
    <Grid>
      <Grid.RowDefinitions>
        <RowDefinition Height="85" />
        <RowDefinition Height="*" />
        <RowDefinition Height="40" />
      </Grid.RowDefinitions>

      <Image Grid.Row="0" Source="Icons/CMWtoolsSplashBanner.png" Height="85" />

      <Grid Grid.Row="1" Margin="18,5,18,5">
        <Grid.RowDefinitions>
          <RowDefinition Height="30" />
          <RowDefinition Height="*" />
        </Grid.RowDefinitions>

        <Grid Grid.Row="0">
          <Grid.ColumnDefinitions>
            <ColumnDefinition Width="Auto" />
            <ColumnDefinition Width="*" />
          </Grid.ColumnDefinitions>
          <TextBlock Grid.Column="0" Text="{Binding ApplicationName}" FontFamily="Arial" FontSize="26" FontWeight="Bold"
                     VerticalAlignment="Center" />
          <TextBlock Grid.Column="1" Text="{Binding ApplicationVersion, StringFormat=' V\{0\}'}" FontFamily="Arial"
                     FontSize="26" FontWeight="Bold" VerticalAlignment="Center" />
        </Grid>

        <Grid Grid.Row="1">
          <Grid.ColumnDefinitions>
            <ColumnDefinition Width="230" />
            <ColumnDefinition Width="*" />
          </Grid.ColumnDefinitions>

          <Grid Grid.Column="0">
            <Image ... >

        </Grid>

          <Grid Grid.Column="1" Margin="10,0,0,0">
            <Grid.RowDefinitions>
              <RowDefinition Height="30" />
              <RowDefinition Height="*" />
              <RowDefinition Height="22" />
            </Grid.RowDefinitions>

            <TextBlock Text="Plug-ins" FontSize="16" FontFamily="Arial" VerticalAlignment="Center" />

            <ListView Grid.Row="1" ItemsSource="{Binding Features}">
              <ListView.Style>
                <Style TargetType="{x:Type ListView}">
                  <Setter Property="BorderBrush" Value="Black" />
                  <Setter Property="BorderThickness" Value="1" />
                  <Setter Property="Foreground" Value="Black" />
                </Style>
              </ListView.Style>
              <ListView.Resources>
                <Style x:Key="ListViewWithoutHeaderStyle" TargetType="{x:Type GridViewColumnHeader}">
                  <Setter Property="Visibility" Value="Collapsed" />
                </Style>
              </ListView.Resources>
              <ListView.View>
                <GridView x:Name="GridViewFeatures" ColumnHeaderContainerStyle="{StaticResource ListViewWithoutHeaderStyle}">
                  <GridViewColumn Header="Id" Width="140">
                    <GridViewColumn.CellTemplate>
                      <DataTemplate>
                        <TextBlock Text="{Binding Id}" FontSize="16" FontFamily="Arial" FontWeight="Bold"
                                   VerticalAlignment="Center" />
                      </DataTemplate>
                    </GridViewColumn.CellTemplate>
                  </GridViewColumn>
                  <GridViewColumn Header="Name" Width="110">
                    <GridViewColumn.CellTemplate>
                      <DataTemplate>
                        <TextBlock Text="{Binding Name}" FontSize="16" FontFamily="Arial" FontWeight="Bold"
                                   VerticalAlignment="Center" />
                      </DataTemplate>
                    </GridViewColumn.CellTemplate>
                  </GridViewColumn>
                  <GridViewColumn Header="Version" Width="100">
                    <GridViewColumn.CellTemplate>
                      <DataTemplate>
                        <TextBlock Text="{Binding Version}" FontSize="16" FontFamily="Arial" FontWeight="Bold"
                                   VerticalAlignment="Center" />
                      </DataTemplate>
                    </GridViewColumn.CellTemplate>
                  </GridViewColumn>
                </GridView>
              </ListView.View>
            </ListView>

            <TextBlock Grid.Row="2" Text="Copyright &#169; 2013 Rohde &amp; Schwarz. All rights reserved." FontFamily="Arial"
                       FontSize="12" HorizontalAlignment="Right" VerticalAlignment="Bottom" />
          </Grid>
        </Grid>
      </Grid>

      <Grid Grid.Row="2" Background="#FFDFE1E5">
        <Grid Grid.Row="1" VerticalAlignment="Center" Margin="18,0,18,0">
          <Grid.ColumnDefinitions>
            <ColumnDefinition Width="Auto" />
            <ColumnDefinition Width="*" />
          </Grid.ColumnDefinitions>
          <TextBlock Grid.Column="0" x:Name="ProgressMessageControl" Text="Loading..." FontSize="12" FontFamily="Arial"
                     VerticalAlignment="Center" />
          <ProgressBar Grid.Column="1" x:Name="ProgressBarControl" Height="16" Margin="10,0,0,0" VerticalAlignment="Center" />
        </Grid>
      </Grid>
    </Grid>
  </Border>
</GraphicalShell:DynamicSplashScreen>

Any help would be appreciated a lot!

How to Type cast User control in View Model captured through some event?

$
0
0

Hi,

 I am facing issues, in TypeCasting the UserControl. In my scenario, the user control contains a TextBox and few buttons. When the LostFocus occurs from User control's Textbox, it raises the PreVIewLostFocus and goes to the respective event statements for execution. Here when, i try to typecast the control appeared in the Sender object, it is not recognized as a User control, instead it's only considered as a TextBox.

XAML code:

<commonviews:MyUC x:Name="uxMyUC" Text ="{Binding UserNameValue,UpdateSourceTrigger=PropertyChanged,Mode=TwoWay}"

Width="415" PreviewLostKeyboardFocusCommand="{Binding LostFocusCommand, Mode=OneWay}" ></commonviews:MyUC>


The PreviewLostFocus is command is handled in View Model as below

 public virtual void LostFocus(System.Windows.RoutedEventArgs e)
        {

                   control = e.Source as Control;

                   //some code

                   if (control is MyUC)
                        {
                            //actions here
                        }

}

How can we correctly type cast the Control ?

Thanks in advance,

Sagar

DataGridTemplateColumn width Resize with Content.

$
0
0

Hi Friends,

I have a DataGrid, In that Defined a DataGridTemplateColumn with Custome View.

DataGrid Column is not Autosizing with its content. Kidnly suggesrt

<DataGrid >

        <DataGrid.Columns>
            <DataGridTemplateColumn Header="test1"  Visibility="{Binding MainVisi}">
                <DataGridTemplateColumn.HeaderTemplate>
                    <StackPanel Grid.Row="1" Orientation="Horizontal">
                        <TextBlock Text="{Binding temp1}" Visibility="{Binding Vis1}" ></TextBlock>
                        <TextBlock Text="{Binding temp2}" Visibility="{Binding vis2}" ></TextBlock>

 <TextBlock Text="{Binding temp3}" Visibility="{Binding vis3}" ></TextBlock>                     </StackPanel>
                </DataGridTemplateColumn.HeaderTemplate>
                <DataGridTemplateColumn.CellTemplate>
                    <DataTemplate>
                        <Border Margin="0">

                            <StackPanel Grid.Row="1" Orientation="Horizontal">
                                <TextBox Text="{Binding tempv1}" Visibility="{Binding Vis1}" Template="{StaticResource temp1}"></TextBox>
                                <TextBox Text="{Binding tempv2}" Visibility="{Binding vis2}" Template="{StaticResource temp2}"></TextBox>

 <TextBox Text="{Binding tempv3}" Visibility="{Binding vis3}" Template="{StaticResource temp2}"></TextBox>                             </StackPanel>
                        </Border>
                    </DataTemplate>
                </DataGridTemplateColumn.CellTemplate>
            </DataGridTemplateColumn>
        </DataGrid.Columns>
    </DataGrid>

So when i hide(Collapsed) first one(temp1, tempv1) Header and Content controls. controls are disappear But Template column is not auto resizing.

Kinmdly Suggest


Jagadish


Animate a property in the DataContext instead of the UIElement that uses that DataContext

$
0
0

The title pretty much describes my question.

I have a CLR object that is used as a DataContext for ListBox items which are hosted on a Canvas.  In the CLR object I have DP's that are bound to the Canvas.Top and Left properties.  Now I want to animate those properties.

What I want to do is create an animation that uses those properties rather than the Top/Left of the ListBoxItems.  Is this possible?


Lloyd Sheen

Mouse Wheel Binding in XAML using MVVM

$
0
0

I am creating an application where the user will be able to use the mousewheel to scroll through database records which are bound using MVVM.

I am trying to bind the mouse wheel scroll to a command in my ViewModel.

I have managed to setup the binding but i do not know how to determine which way the wheel was scrolled. Using the code behind, i know about using the Delta value, but how do i do this using XAML & MVVM?

<i:Interaction.Triggers><i:EventTrigger EventName="MouseWheel"><i:InvokeCommandAction Command="{Binding mouseScrollCommand}"/></i:EventTrigger></i:Interaction.Triggers>

public void mouseScrollCommand
{
//If mouseScrollUp, goto previous record
//If mouseScrollDown, goto next record
}
Any help would be much appreciated. Thanks

WPF: how to reference LinearGradientBrush in ViewModel class?

$
0
0

Our WPF application includes plate control which constains 96 vials.

Depend on each vial property, the vial background color changes.

We used to define default vial color as string and directly bind it to the vial' background.

private string _fillColor = "#000605";     //black

However, our industry designer want to change the vial default color as LinearGradientBrush


<LinearGradientBrush x:Key="VialBrush" StartPoint="0.5,0" EndPoint="0.5,1"><GradientStop Offset="1" Color="#FF6E6E6E" /><GradientStop Color="#FFC5C5C5" /></LinearGradientBrush>

So We need to reference LinearGradientBrush in ViewModel class.

How do we reference LinearGradientBrush in ViewModel?

Should we define LinearGradientBrush in Style.xaml and reference it by looking up the resource key?

Or should we directly define LinearGradientBrush in the ViewModel? Thx!


JaneC


Build month! So much new to know! WPF Gurus needed - to help catalogue all this new stuff!

$
0
0

A wonderful week of news and new technology advances from Build this week have filled our minds with new possiblilities!

So much to play with!

Can you help us document some of the new features coming out over the next year?

Do you have a good grasp on how we should now be doing that thing that we do?

Did you find a knowledge gap in the web for the new features now available?

This is a great chance to jump into the TechNet Guru competition and stamp your authority on your favoutrite subject.

All you have to do is add an article to TechNet Wiki from your own specialist field. Something that fits into one of the categories listed on the submissions page. Copy in your own blog posts, a forum solution, a white paper, or just something you had to solve for your own day's work today.

Drop us some nifty knowledge, or superb snippets, and become MICROSOFT TECHNOLOGY GURU OF THE MONTH!

This is an official Microsoft TechNet recognition, where people such as yourselves can truly get noticed!

HOW TO WIN

1) Please copy over your Microsoft technical solutions and revelations toTechNet Wiki.

2) Add a link to it on THIS WIKI COMPETITION PAGE (so we know you've contributed)

3) Every month, we will highlight your contributions, and select a "Guru of the Month" in each technology.

If you win, we will sing your praises in blogs and forums, similar to the weekly contributor awards. Once "on our radar" and making your mark, you will probably be interviewed for your greatness, and maybe eventually even invited into other inner TechNet/MSDN circles!

Winning this award in your favoured technology will help us learn the active members in each community.

Below are February's mighty winners and contenders. We should have March's winners by about mid month.

Guru Award BizTalk Technical Guru - February 2016  

Gold Award Winner

Steef-Jan WiggersBizTalk Server ConvoySandro Pereira: "Explaining what it is and its concepts, it as well, so important as explain how it's done. Very good choice of topic, really well explained and in clearly way. Great job Steef-Jan. For me the best of the month. "
Ed Price: "The diagrams really bring this alive!"
LG: "It is really full description of one of the complex idea in BizTalk." 

Silver Award Winner

Eldert GrootenboerDeploying web services with BizTalk Deployment FrameworkEd Price: "Thank you! This is a much-needed scenario that's very well written!"
Sandro Pereira: "Again well explain and in clearly way, an excellent article for BTDF lovers :). Great job."

Bronze Award Winner

lanaxContinuous deployment - BizTalk Applications built using BTDF and Octopus deploySandro Pereira: "Good article, nice to see people right about new tools and how that they can add value."
Ed Price: "Great scenario on continuous deployment! The code could use a breakdown to explain the parts, but the introduction is very thorough!"

 

Guru Award Forefront Identity Manager Technical Guru - February 2016  

Gold Award Winner

Jeff IngallsMIM 2016: Privileged Access Management (PAM) - FAQEd Price: "Great resource to come back to!"
Søren Granfeldt: "Good start"

Silver Award Winner

Wim BeckFIM2010: Selective Import Attribute FlowSøren Granfeldt: "Nice ideas...."
Ed Price: "Great scenario and thorough Intro and Possible Solutions sections! Could benefit from a breakdown of the code or a conclusion. Great formatting!"

Guru Award Microsoft Azure Technical Guru - February 2016  

Gold Award Winner

Steef-Jan WiggersAccess Azure Redis Cache with an API AppJH: "Nice article about combining Redis and API Apps, especially the integration of Swagger is great."

Silver Award Winner

XAML GuyIoT Suite Under The Hood - Predictive MaintenanceJH: "Have played with the template myself. Great to see an article about it. Would love to see an article on how to customize the template in more detail."

Bronze Award Winner

Samir FarhatHow to access an ARM Azure virtual machine from InternetJH: "Had the problem myself in the beginning. Found a way through the portal. Good to see PowerShell scripts to do it in a repeatable fashion."

 

Guru Award Miscellaneous Technical Guru - February 2016  

Gold Award Winner

Geetanjali AroraAn Introduction to Microsoft Graph APIRichard Mueller: "Very well explained with good detailed steps. I like the references."
Peter Laker: "Top marks Geentanjali, nice article"

Silver Award Winner

Gaurav Kumar AroraCruds in NancyFx using ASP.Net and FluentNHibernate Using Repository PatternRichard Mueller: "Lots of good code and images. Grammar needs work."
Peter Laker: "Very interesting, thanks Gaurav"

Bronze Award Winner

SYEDSHANUASP.NET MVC User Role Base Menu Management Using WEB API And AngularJS

Peter Laker: "Wow great article!"
Richard Mueller: "Lots of code and detailed steps."

 

Guru Award SharePoint 2010 / 2013 Technical Guru - February 2016  

Gold Award Winner

Nathanaël StassartOneDrive : Next Generation Sync Client Deployment guideEd Price: "Wow this is thorough! Great formatting, color-coding the tables, including images, code formatting, and a general breakdown of each step, in depth!"
Richard Mueller: "Good use of Wiki guidelines and great links. The "See Also" should be Wiki articles, this is really "Other Resources"."

Silver Award Winner

Rakhi JainSharePoint 2013 : Customize Document Library TreeView Navigation BarRichard Mueller: "Great use of Wiki guidelines."
Ed Price: "Short and sweet. Great scenario and good use of an image and code formatting! Very clear steps."

Bronze Award Winner

TenPartSharePoint 2010: Updating TermStore using PowerShellEd Price: "Good details and formatting. Could benefit from a TOC, breakdown of the code, and a See Also section at the end for Wiki links. Thank you!"
Richard Mueller: "Good code. We could use some references."

Guru Award Small Basic Technical Guru - February 2016  

Gold Award Winner

Ed Price - MSFTSmall Basic 1.2: Installation GuideRichard Mueller: "Good use of Wiki guidelines. Great images that detail the steps."

Silver Award Winner

Nonki TakahashiSmall Basic: DesktopMichiel Van Hoorn: "Realy cool to interact with Windows components."
Richard Mueller: "Excellent use of Wiki guidelines"

Bronze Award Winner

Ed Price - MSFTSmall Basic: How to Publish Your ProgramRichard Mueller: "Good images and useful information."
Michiel Van Hoorn: "Sharing is caring. How much fun is it to share your code with friends and family"

Guru Award SQL BI and Power BI Technical Guru - February 2016  

Gold Award Winner

Benchmark your SQL Server instanceSSIS - Transfer data from Multiple tables using a single DFTPT: "Vinay, this is a very creative and useful solution to a difficult problem. I've seen multiple ETL frameworks for SSIS over the years and I think your approach is quite sound. Congratulations on winning the Guru award this month!"
RB: "Nice walkthrough and solution to a common scenario"

Silver Award Winner

Visakh16SSRS Tips : Implementing OR Based Logic for Dataset FiltersPT: "Visakh, thanks for posting this useful information about report filters. This is a powerful feature that takes a bit of effort to use effectively."

Bronze Award Winner

Greg DecklerDates Prior to 1900 in DAXPT: "Greg, thanks for this insightful contribution. The date range limit is something I run into all the time and is a tough problem to solve. This is a good work-around technique."
RB: "Interesting workaround"

Guru Award SQL Server General and Database Engine Technical Guru - February 2016  

Gold Award Winner

FLaufferWorkaround for Delay in Transaction Log Truncation: Snapshot ReplicationUR: "good and short explanation of a common problem with transaction logs."
DRC: "The article talks about executing sp_repldone as workaround which can be used only as a last resort. "

Guru Award System Center Technical Guru - February 2016  

Gold Award Winner

Darren JoyceSCOM Reset Health on Alert CloseAlan Carlos: "Thanks for article!"
Ed Price: "Great depth and details in this article! "

Guru Award Transact-SQL Technical Guru - February 2016  

Gold Award Winner

Olaf HelperSQL Server: Implementation of N-Gram Search Index

Richard Mueller: "Very interesting ideas for search. Good use of Wiki guidelines"

Ed Price: "I love how you break down the code and explain it so thoroughly!"

Silver Award Winner

Natig GurbanovSQL SERVER:Using Datalength() function

Richard Mueller: "Interesting. This could use some references."

Ed Price: "Great topic. It could benefit from more explanation of the code."

Guru Award Universal Windows Apps Technical Guru - February 2016  

Gold Award Winner

George ChondrompilasReal-time chat UWP application using Azure Mobile App and SignalR

JH: "Nice and simple example. Would love to see more examples using SignalR."

Ed Price: "The breakdown of the code and the images add great value."

Silver Award Winner

Magnus (MM8)UWP: Disabling Selection Of Items In a ListView

JH: "Nice workaround for disabling items."

Ed Price: "Fantastic formatting and great explanations!"

Guru Award Visual Basic Technical Guru - February 2016  

Gold Award Winner

.paul.calc2 - A VB.Net OOP CalculatorMR: "Nice example!"
Richard Mueller: "Interesting ideas. Lots of well documented code. Good use of Wiki guidelines."

Silver Award Winner

SYEDSHANUControl Chart Using VB.NetMR: "Nice and easy to use chart!"
Richard Mueller: "Nice GUI. Lots of code."

Guru Award Visual C# Technical Guru - February 2016  

Gold Award Winner

SYEDSHANUASP.NET 5 CRUD using Scaffolding and Entity FrameworkCarmelo La Monica: "Very interesting article, very detailed and good images and video."
Jaliya Udagedara: "Good article with a detail explanation. And the sample code is available in MSDN Code Gallery. Hint: you can use EF itself to generate the database and seeding the data rather than running the scripts."

Silver Award Winner

Emiliano MussoBinary Clock in C# and WPFJaliya Udagedara: "This is interesting. Great explanation using code snippets, images and a video. And the sample code is available in MSDN Code gallery. Just great!"
Carmelo La Monica: "Congratulation, very impressive imeges, good video dimostration and lot of funny :)"

Bronze Award Winner

Brian SeekfordHow to access legacy forms checkboxes and ActiveX checkboxes in Word using C#! by Brian SeekfordJaliya Udagedara: "Would love to have a better formatting in the article and of course a sample to download and try it out."
Carmelo La Monica: "Good article. it can benefit format C# code and table of contents."

 

Guru Award Wiki and Portals Technical Guru - February 2016  

Gold Award Winner

Ed Price - MSFTWiki: Dynamics CRM PortalRichard Mueller: "A great portal with great links."

Guru Award Windows PowerShell Technical Guru - February 2016  

Gold Award Winner

Pierre-Alexandre Braeken MCSERSA with PowerShell - PowerRSAEd Price: "Great depth! This article will be a good resource to return to!"

Silver Award Winner

Richard MuellerPowerShell AD Module Cmdlets Cannot Clear, Add, Remove or Replace Back Link AttributesEd Price: "Beautiful formatting, and great use of the different sections!"

Guru Award Windows Presentation Foundation (WPF) Technical Guru - February 2016  

Gold Award Winner

Andy ONeillCombobox Matching Complex Type

Peter Laker: "Nice work Andy. Well presented and useful, just like you!"

Ed Price: "I love how Andy's articles break down each snippet like this!"

Silver Award Winner

Brian SeekfordHow to display a different value in a WPF combobox based on selection i..e None instead of blank by Brian Seekford

Peter Laker: "Thank you Brian, good contribution"

Ed Price: "Good scenario. Could benefit from See Also links and code explanations. Good article!"

Guru Award Windows Server Technical Guru - February 2016  

Gold Award Winner

Kia Zhi Tang (Ryen Tang)Nano Server: Deploying an Internet Information Services (IIS) Web ServerAlan Carlos: "Great article! Congratulations!!! Nano Server is amazing!"
JM: "This is an excellent article on Nano server, thanks for your contribution"
Richard Mueller: "Good references and step by step instructions."
Mark Parris: "Good insight into the one of Nano server's capabilities."

Silver Award Winner

Mahdi TehraniLoad balancers and Active DirectoryMark Parris: "Critical information that people need to be aware of."
JM: "This is a good article that could use an edit pass for clarity"
Richard Mueller: "I share your concern for the need of a load balancer. Any AD integrated app should use AD group memberships."

Good luck!
Pete Laker


#PEJL
Got any nice code? If you invest time in coding an elegant, novel or impressive answer on MSDN forums, why not copy it over toTechNet Wiki, for future generations to benefit from! You'll never get archived again, and you could win weekly awards!

Have you got what it takes o become this month's TechNet Technical Guru? Join a long list of well known community big hitters, show your knowledge and prowess in your favoured technologies!


Way to edit Grid row

$
0
0
Hi,
To one DataGrid, what is the better way to edit one row? Is there any way, like to show one Popup window, once Edit button of the row, has been clicked? Is there any good example to do this?

Many Thanks & Best Regards, Hua Min


ScrollViewer can not be click through.

$
0
0

I can click both c1_button and c2_button in Example 2,

but, I can't click the c1_button in Example 1. Why?


Example 1:

<Grid Width="300" Height="300"><Button Name="c1_button" Width="50" Height="50"></Button><ScrollViewer Name="c2" Width="150" Height="150"><ScrollViewer.Style><Style TargetType="{x:Type ScrollViewer}"><Setter Property="Template"><Setter.Value><ControlTemplate TargetType="{x:Type ScrollViewer}">
                                        <Grid>
                                            <Border BorderBrush="Blue" BorderThickness="25"></Border>
                                            <Button Name="c2_button" Width="50" Height="50" VerticalAlignment="Bottom" HorizontalAlignment="Right"></Button>
                                        </Grid></ControlTemplate></Setter.Value></Setter></Style></ScrollViewer.Style></ScrollViewer></Grid>




Example 2:

<Grid Width="300" Height="300"><Button Name="c1_button" Width="50" Height="50"></Button><TabControl Name="c2" Width="150" Height="150"><TabControl.Style><Style  TargetType="{x:Type TabControl}"><Setter Property="Template"><Setter.Value><ControlTemplate TargetType="{x:Type TabControl}">
                                        <Grid>
                                            <Border BorderBrush="Blue" BorderThickness="25"></Border>
                                            <Button Name="c2_button" Width="50" Height="50" VerticalAlignment="Bottom" HorizontalAlignment="Right"></Button>
                                        </Grid></ControlTemplate></Setter.Value></Setter></Style></TabControl.Style></TabControl></Grid>





How to export data from datagrid in WPF to PDF with C# ?

$
0
0

hi all ! Actually i've an application in C# with WPF and i want to export to PDF a datagrid. I've found many tuto with DatagGridView but it's not the same way for WPF. this is my last try with iTextSharp :

dfPTable table = new PdfPTable(CmdGrid.Columns.Count);

            for (int j = 0; j < CmdGrid.Columns.Count; j++)
            {
                table.AddCell(new Phrase(CmdGrid.Columns[j].Header.ToString()));
            }

            table.HeaderRows = 1;

            for (int i = 0; i < CmdGrid.Items.Count; i++)
            {
                for (int k = 0; k < CmdGrid.Columns.Count; k++)
                {
                    if (CmdGrid[k, i].value != null)
                    {
                        table.AddCell(new Phrase(CmdGrid[k, i ].value.ToString()));
                    }
                }
            }

            pdfcommande.Add(table);

            iTextSharp.text.Paragraph firstpara = new iTextSharp.text.Paragraph("Test 1");
            pdfcommande.Add(firstpara);
            pdfcommande.Close();

Thank you in advance for any help !!

TreeView use with the ComboBox

$
0
0

I am Transferring the TextBox the values when I Selected from the ComboBox.

    public class Observable : INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged;

        protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
        {
            var handler = PropertyChanged;
            if (handler != null)
            {
                handler(this, new PropertyChangedEventArgs(propertyName));
            }
        }
    }

And

 public class TblMusteri:Observable
    {
        private Int64 musteriId;
        public Int64 MusteriId
        {
            get { return musteriId; }
            set { musteriId = value; OnPropertyChanged("MusteriId"); }
        }
        private string ad;
        public string Ad
        {
            get { return ad; }
            set
            {
                ad = value;
                this.OnPropertyChanged("Ad");
            }
        }
        private string soyad;
        public string Soyad
        {
            get { return soyad; }
            set { soyad = value; this.OnPropertyChanged("Soyad"); }
        }
        private string unvan;
        public string Unvan
        {
            get { return unvan; }
            set { unvan = value; OnPropertyChanged("Unvan"); }
        }
        private string telefon;
        public string Telefon
        {
            get { return telefon; }
            set { telefon = value; OnPropertyChanged("Telefon"); }
        }

    }

And

 public class MusteriViewModel : Observable
    {
        public ObservableCollection<TblMusteri> musteriler = new ObservableCollection<TblMusteri>();
        public ObservableCollection<TblMusteri> Musteriler
        {
            get
            {
                return musteriler;
            }
            set
            {
                musteriler = value;
                OnPropertyChanged("Musteriler");
            }
        }
        private TblMusteri selectedItem = new TblMusteri();
        public TblMusteri SelectedItem
        {
            get
            {
                return selectedItem;
            }
            set
            {
                selectedItem = value;
                OnPropertyChanged("SelectedItem");
            }
        }
        public MusteriViewModel()
        {
            using (SqlConnection conn = new SqlConnection(@"Data Source=.\SQLEXPRESS;Initial Catalog=CustomerBase;Integrated Security=True"))
            {
                using (SqlCommand cmd = new SqlCommand())
                {
                    cmd.Connection = conn;
                    cmd.CommandText = "Select* From MusteriBase Order by AD ASC;";
                    conn.Open();
                    SqlDataReader dr = cmd.ExecuteReader();
                    while (dr.Read() == true)
                    {
                        musteriler.Add(new TblMusteri()
                        {
                            Ad = dr["AD"].ToString(),
                            Soyad = dr["SOYAD"].ToString(),
                            Unvan = dr["UNVAN"].ToString(),
                            Telefon = dr["TELEFON"].ToString(),
                            MusteriId = (Int64)dr["mustID"]
                        });
                    }
                    cmd.Dispose();
                }
                conn.Close();
            }
        }
    }
<Canvas><ComboBox x:Name="cmbMusteriListele"
					  ItemsSource="{Binding Musteriler}"
					  SelectedValue="{Binding SelectedItem.MusteriId,Mode=TwoWay}"
					  DisplayMemberPath="Ad"
					  Width="236"
					  Height="26"
					  Canvas.Left="19"
					  Canvas.Top="24"/><TextBox TextWrapping="Wrap"
					 Text="{Binding ElementName=cmbMusteriListele,Path=SelectedItem.Ad,UpdateSourceTrigger=PropertyChanged}"
					 Width="236"
					 Canvas.Left="19"
					 Canvas.Top="214"
					 Height="30"/><TextBox Text="{Binding ElementName=cmbMusteriListele, Path=SelectedItem.Ad}"
					 Background="Beige" Width="236"
					 Canvas.Left="19"
					 Canvas.Top="74"
					 Height="30"/><TextBox Height="30"
					 Canvas.Left="19"
					 TextWrapping="Wrap"
					 Text="{Binding ElementName=cmbMusteriListele, Path=SelectedItem.Soyad}"
					 Canvas.Top="109"
					 Width="236"/><TextBox Text="{Binding ElementName=cmbMusteriListele, Path=SelectedItem.Unvan}"
					 Background="RosyBrown"
					 Width="236"
					 Canvas.Left="19"
					 Canvas.Top="144"
					 Height="30"/><TextBox Text="{Binding ElementName=cmbMusteriListele, Path=SelectedItem.Telefon}"
					 Background="Beige"
					 Width="236"
					 Canvas.Left="19"
					 Canvas.Top="179"
					 Height="30"/><TreeView   x:Name="CustomerTreeView"
						Cursor="Hand"
						Background="White"
						Height="285"
						Canvas.Left="273"
						Canvas.Top="24"
						Width="126"><TreeView.Resources><SolidColorBrush x:Key="{x:Static SystemColors.HighlightBrushKey}" Color="Transparent"/><SolidColorBrush x:Key="{x:Static SystemColors.HighlightTextBrushKey}" Color="Black"/></TreeView.Resources></TreeView></Canvas>
       public MainWindow()
        {
            InitializeComponent();
            DataContext = new MusteriViewModel();

        }

How do I transfer the values the TreeView while the ComboBox ıt is Selected ?

Thanks;




Understanding a piece of code related to ICommand implementation

$
0
0

Hi,

I have got this piece of code from internet. I could not understand this.

https://github.com/briannoyes/WPFMVVM-StarterCode/blob/master/ZzaDashboard/ZzaDashboard/RelayCommand.cs

public class RelayCommand : ICommand
    {
        private Action _TargetExecuteMethod;
        private Func<bool> _TargetCanExecuteMethod;

        public RelayCommand(Action executeMethod)
        {
            _TargetExecuteMethod = executeMethod;
        }

        public RelayCommand(Action executeMethod, Func<bool> canExecuteMethod)
        {
            _TargetExecuteMethod = executeMethod;
            _TargetCanExecuteMethod = canExecuteMethod;
        }

        public void RaiseCanExecuteChanged()
        {
            CanExecuteChanged(this, EventArgs.Empty);
        }

        #region ICommand Members

        bool ICommand.CanExecute(object parameter)
        {
            if (_TargetCanExecuteMethod != null)
            {
                return _TargetCanExecuteMethod();
            }
            if (_TargetExecuteMethod != null)
            {
                return true;
            }
            return false;
        }

        // Beware - should use weak references if command instance lifetime is longer than lifetime of UI objects that get hooked up to command 
        // Prism commands solve this in their implementation 
        public event EventHandler CanExecuteChanged = delegate { };

        void ICommand.Execute(object parameter)
        {
            if (_TargetExecuteMethod != null)
            {
                _TargetExecuteMethod();
            }
        }

        #endregion
    }

    public class RelayCommand<T> : ICommand
    {
        private Action<T> _TargetExecuteMethod;
        private Func<T, bool> _TargetCanExecuteMethod;

        public RelayCommand(Action<T> executeMethod)
        {
            _TargetExecuteMethod = executeMethod;
        }

        public RelayCommand(Action<T> executeMethod, Func<T, bool> canExecuteMethod)
        {
            _TargetExecuteMethod = executeMethod;
            _TargetCanExecuteMethod = canExecuteMethod;
        }

        public void RaiseCanExecuteChanged()
        {
            CanExecuteChanged(this, EventArgs.Empty);
        }

        #region ICommand Members

        bool ICommand.CanExecute(object parameter)
        {
            if (_TargetCanExecuteMethod != null)
            {
                T tparm = (T) parameter;
                return _TargetCanExecuteMethod(tparm);
            }
            if (_TargetExecuteMethod != null)
            {
                return true;
            }
            return false;
        }

        // Beware - should use weak references if command instance lifetime is longer than lifetime of UI objects that get hooked up to command 
        // Prism commands solve this in their implementation 
        public event EventHandler CanExecuteChanged = delegate { };

        void ICommand.Execute(object parameter)
        {
            if (_TargetExecuteMethod != null)
            {
                _TargetExecuteMethod((T) parameter);
            }
        }

        #endregion
    }

But this works fine. I can use it like this.

 public RelayCommand TestRelayCommand { get; set; }
        public MainWindowViewModel()
        {
            TestRelayCommand = new RelayCommand(ShowMyView);
        }
        private void ShowMyView()
        {
            CurrentViewModel = _testViewModel;
        }

I did not understand the code. Can someone explain me how does this works? what is the execution flow?

Regards,

Populating ComboBox with Images inside folder in project

$
0
0

Ok, the images are inside a folder that is "inside the project" and the build action is resource. My question is how do I put those icons in a comboBox?

And I think this is not a duplicate because I did search and only find results where the folder is not embedded in the project.

Image: https://social.msdn.microsoft.com/Forums/getfile/835115

This is my code: (I got this from searching but I forgot the website)

List<object> items = new List<object>();
var assembly = Assembly.GetExecutingAssembly();
var resourcesName = assembly.GetName().Name + ".g.resources";
var stream = assembly.GetManifestResourceStream(resourcesName);
var resourceReader = new ResourceReader(stream);
foreach(DictionaryEntry item in resourceReader)
{
    items.Add(item.Value);
}
comboBox.ItemsSource = items;

//it's working but this is what I get
icons/bbinq.ico
icons/bbt.ico
icons/begr.ico
icons/logo 1.ico
icons/logo.ico
icons/mepv1.ico
icons/mepv2.ico
icons/sbtm.ico

//what I need is like this (case sensitive also)
BBINQ.ico
BBT.ICO
BEGR.ico
LOGO 1.ICO
LOGO.ICO
MEPV1.ico
MEPV2.ico
SBTM.ICO
I just need the filenames...

Delete configuration file

$
0
0

Hi, I have a project written in c# wpf.
When the software is run the file softwarename.exe.config is created in the app folder and the file softwarename.exe.config is created in the folder C:\Users\username\AppData\Local\VirtualStore\Program Files\softwarename.

I have the need at the next relese to delete this files. how can I do?

Thanks in advanced.


Listview row colors

$
0
0
<Window x:Class="WpfApplication1.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="367" Width="614"><Grid x:Name="gridHome" HorizontalAlignment="Left" Height="300" Margin="0,10,-52,-318" VerticalAlignment="Top" Width="600"><ListView x:Name="lsvOrder" Height="300" Margin="0,10,0,-10" VerticalAlignment="Top"><ListView.View><GridView><GridViewColumn Header="No" Width="60" DisplayMemberBinding="{Binding NUMBER}"></GridViewColumn><GridViewColumn Header="Order No" Width="120" DisplayMemberBinding="{Binding ORDER}"></GridViewColumn><GridViewColumn Header="table" Width="120" DisplayMemberBinding="{Binding TABLE}"></GridViewColumn><GridViewColumn Header="Order Info" Width="150" DisplayMemberBinding="{Binding ORDER_TIMER}"></GridViewColumn><GridViewColumn Header="Table Info" Width="150" DisplayMemberBinding="{Binding TABLE_TIMER}"></GridViewColumn></GridView></ListView.View></ListView></Grid></Window>


public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();

            lsvOrder.Items.Add(new ListViewData("1", "0001", "T1", "Timer1", "Timer4"));
            lsvOrder.Items.Add(new ListViewData("2", "0002", "T2", "Timer2", "Timer5"));
            lsvOrder.Items.Add(new ListViewData("3", "0003", "T3", "Timer3", "Timer6"));
        }
    }

    public class ListViewData
    {
        public ListViewData(string col1, string col2, string col3, string col4, string col5)
        {
            NUMBER = col1;
            ORDER = col2;
            TABLE = col3;
            ORDER_TIMER = col4;
            TABLE_TIMER = col5;
        }

        public string NUMBER { get; set; }
        public string ORDER { get; set; }
        public string TABLE { get; set; }
        public string ORDER_TIMER { get; set; }
        public string TABLE_TIMER { get; set; }
    }

Hello~

how to change row background colour?

Thecolorwillchangefrequently.

I want Code(C#).

Note: The color settingswill bein color table.

Note: Colors arechanged by acertain time.

Please, answer.




Language Translation for strings in DataTemplates

$
0
0

Hi,

I have a wpf application in which I am using MarkupExtension for language translation. For string translation present as binding, I am using a converter. The code works fine for binding but fails when the binding is present in Datatemplate. I am not getting how to handle the string translation and return correct value from provideValue function. Below is the code: -

<ComboBox
                Name="LanguageCombo"
                ItemsSource="{Binding Languages}"
                Margin="8"
                DisplayMemberPath="NativeName"
                SelectedItem="{Binding SelectedLanguage, Mode=TwoWay}"></ComboBox><TextBlock Text="{local:Translate LocalizedByMarkupExtension}" Margin="8" /><TextBlock Text="{local:Translate {Binding Color}}" Margin="8" /><ComboBox Foreground="White"
                          Width="154"
                          Height="28px"
                          FontSize="13px"
                          VerticalContentAlignment="Center" ItemsSource="{Binding SortOptionsListView}"
                          IsSynchronizedWithCurrentItem="True"><ComboBox.ItemTemplate><DataTemplate><TextBlock Text="{local:Translate {Binding SortOptionID}}" Foreground="Black"/></DataTemplate></ComboBox.ItemTemplate></ComboBox>


    public class TranslateExtension : MarkupExtension
    {
        private WeakReference bindObj;
        private WeakReference targetObject;
        private DependencyProperty targetProperty;

        #region Construction

        /// <summary>
        /// Initializes a new instance of the <see cref="TranslateExtension"/> class.
        /// </summary>
        /// <param name="key">The key.</param>
        public TranslateExtension(object objToBeTranslated)
        {
            if (objToBeTranslated is string)
            {
                Key = objToBeTranslated as string;
            }
            else
            {
                bindObj = new WeakReference(objToBeTranslated as Binding);
                var _tempBind = objToBeTranslated as Binding;
                if (_tempBind.Converter != null)
                {
                    IValueConverter _existingConverter = _tempBind.Converter;
                    var _chainedConverter = new ValueConverterGroup();
                    _chainedConverter.Converters.Add(_existingConverter);
                    // FIXME - Take from a static resource
                    _chainedConverter.Converters.Add(new TranslationValueConverter());
                    _tempBind.Converter = _chainedConverter;
                }
                else
                {
                    // FIXME - Do not re-create. Take from a static resourceagbhb
                    _tempBind.Converter = new TranslationValueConverter();
                }
            }
        }

        public TranslateExtension()
        {
        }

        #endregion

        [ConstructorArgument("Key")]
        public string Key { get; set; }

        private Binding BindObj
        {
            get
            {
                if (null != bindObj && bindObj.IsAlive)
                {
                    return bindObj.Target as Binding;
                }
                else
                {
                    return null;
                }
            }
        }

        /// <summary>
        /// See <see cref="MarkupExtension.ProvideValue" />
        /// </summary>
        public override object ProvideValue(IServiceProvider pServiceProvider)
        {
            if (null != Key)
            {
                var _service = pServiceProvider.GetService(typeof(IProvideValueTarget)) as IProvideValueTarget;
                if (_service != null)
                {
                    targetProperty = _service.TargetProperty as DependencyProperty;
                    if (targetProperty != null)
                    {
                        if (_service.TargetObject is DependencyObject)
                        {
                            targetObject = new WeakReference(_service.TargetObject);
                            TranslationHelper.Instance.AddTargetExtension(this);
                        }
                    }
                }
                return TranslationManager.Instance.Translate(Key);
            }
            else
            {
                //check if the extension is evaluated for template or real control
                //we just need to test whether the type of TargetObject is System.Windows.SharedDP
                var target = pServiceProvider.GetService(typeof(IProvideValueTarget)) as IProvideValueTarget;
                if (target != null)
                {
                    if (target.TargetObject.GetType().FullName == "System.Windows.SharedDp")
                    {
                        return this;
                    }
                }
                if (BindObj == null)
                    return null;
                //Do this only when you need dynamic language switching
                var _be = BindObj.ProvideValue(pServiceProvider) as BindingExpression;
                TranslationHelper.Instance.AddBindingExpression(_be);
                return _be;
            }
        }

        /// <summary>
        /// Updates the value of the localized object.
        /// </summary>
        internal void UpdateTargetValue()
        {
            if (targetProperty != null)
            {
                if (targetObject.IsAlive)
                {
                    var _dTargetObject = targetObject.Target as DependencyObject;
                    if (_dTargetObject != null)
                    {
                        //;
                        var _element = _dTargetObject as UIElement;
                        if (null != _element)
                        {
                            _element.Dispatcher.Invoke(
                                new Action(
                                    () =>
                                    {
                                        _dTargetObject.SetValue(targetProperty,
                                                                TranslationManager.Instance.Translate(Key));
                                    }));
                        }
                    }
                }
            }
        }
    }
   [ValueConversion(typeof (String), typeof (String))]
    public class TranslationValueConverter : IValueConverter
    {
        #region IValueConverter Members

        object IValueConverter.Convert(
            object pValue, Type pTargetType, object pParameter, CultureInfo pCulture)
        {
            return TranslationManager.Instance.Translate(pValue as string) as string;
        }

        object IValueConverter.ConvertBack(
            object pValue, Type pTargetType, object pParameter, CultureInfo pCulture)
        {
            throw new NotSupportedException("ConvertBack not supported.");
        }

        #endregion
    }
 

Regards,

Sharda.

What is the best way to add caching in WPF app

$
0
0

Dear all,

I have a wpf application which is connected to Azure through web service in order to collect data.

I have notice that with free edition of SQL database you are limited to number of outpout  size you can get from the azure limited to 160mb per day.

I was planning from that point to try to implement a good caching when dealing with data that I donwload from Azure db.

What could be the way to implement those caching n order to avoid pinging the portal for new data if no need ?

Sample will help

regards 

WPF Listbox item navigating using keyboard

$
0
0

I have a Listbox control in my XAML window which will show around 500 items at runtime. I need to be able to navigate the list using the keyboard.

For example in Windows Explorer, when we type a key "a" it will automatically select an item which start with the key a. This will provide more usability to user. I have done this by IsTextSearchEnabled but if there are items starting with "a" and "aa" in the list of items, then it navigates to the item starting with "aa" when I type "a" second time. It is not navigating to next item that starts with "a". I want it to navigate to next item that starts with a. Does anyone know how to solve this?

Here is my code so far:

<ListViewx:Name="lstOS2200Items"Width="auto"Margin="15,8,15,2"Grid.Column="0"Grid.Row="1"VerticalContentAlignment="Stretch"VerticalAlignment="Stretch"SelectionChanged="lstOS2200Items_SelectionChanged"HorizontalContentAlignment="Stretch"HorizontalAlignment="Stretch"KeyDown="lstOS2200Items_KeyDown"IsTextSearchEnabled="True"TextSearch.TextPath="ElementName"SelectionMode="Single">

Open a file from a protected zip file thought a hyperlink (DotNetZip)

$
0
0

Hey guys,

So i need some help with my wpf application. i have a datagrid(see below) and in that datagrid i have some url's.

When you click on a url it links to a file that's inside of a protected zip file. the problem is that i cant open the file because it's inside the protected zip file and i needs to stay inside of the zip file.

XAML code:

<DataGrid AutoGenerateColumns="False" IsReadOnly="True" x:Name="gvData" SelectionMode="Single" FontSize="15" Padding="5" Background="white" Margin="230,178,0,10" Grid.RowSpan="2"><DataGrid.Columns><DataGridTextColumn Binding="{Binding media_name}" Header="Name" MaxWidth="150" /><DataGridHyperlinkColumn Binding="{Binding media_url}" Header="Url"><DataGridHyperlinkColumn.ElementStyle><Style><EventSetter Event="Hyperlink.Click" Handler="Hyperlink_Click"/></Style></DataGridHyperlinkColumn.ElementStyle></DataGridHyperlinkColumn><DataGridTextColumn Binding="{Binding media_terms}" Header="Terms" MaxWidth="150" /></DataGrid.Columns></DataGrid>

i use the Dotnetzip class library for the zipping. How can i open the file that's inside the protected zip file, in it's default program by clicking on the hyperlink. I tryed the extract option on the website of dotnetzip but it doesn't work.

c# CODE:

private void Hyperlink_Click(object sender, RoutedEventArgs e)
        {
            Hyperlink link = (Hyperlink)e.OriginalSource;
            Process.Start(link.NavigateUri.AbsoluteUri);
        }



Viewing all 18858 articles
Browse latest View live


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