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

wpf windows size to content

$
0
0

hi i have this xmal(wpf) code and i cant make the window size to content:

<Window x:Class="OneSpot.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:OneSpot"
        mc:Ignorable="d"
        Title="OneSpot BETA" Height="279.195" Width="468.333" Icon="hotspot-icon.ico"><Grid Margin="0,0,0,-2"><Grid.ColumnDefinitions><ColumnDefinition Width="27*"/><ColumnDefinition Width="88*"/></Grid.ColumnDefinitions><Button x:Name="btn_start" Content="start" HorizontalAlignment="Left" Margin="10,55,0,0" VerticalAlignment="Top" Width="134" Height="36" Click="btn_start_Click" Grid.ColumnSpan="2"/><Button x:Name="btn_stop" Content="stop" HorizontalAlignment="Left" Margin="10,96,0,0" VerticalAlignment="Top" Width="134" Height="36" Click="btn_stop_Click" Grid.ColumnSpan="2"/><Button x:Name="btn_exit" Content="exit" HorizontalAlignment="Left" Margin="10,137,0,0" VerticalAlignment="Top" Width="134" Height="36" Click="btn_exit_Click" Grid.ColumnSpan="2"/><Button x:Name="btn_see" Content="see your settings" HorizontalAlignment="Left" Margin="10,178,0,0" VerticalAlignment="Top" Width="134" Height="36" Click="btn_see_Click" Grid.ColumnSpan="2"/><Label x:Name="label" Content="beta" HorizontalAlignment="Left" Height="102" Margin="101.333,46,0,0" VerticalAlignment="Top" Width="199" FontSize="74.667" Grid.Column="1"/><Button x:Name="btn_form2" Content="setup your Settings" HorizontalAlignment="Left" Margin="10,8,0,0" VerticalAlignment="Top" Width="134" Height="40" Click="btn_form2_Click" Grid.ColumnSpan="2"/><Label x:Name="label1" Content="Copyright © reuven (MySpot)" HorizontalAlignment="Left" Margin="-1,219,0,0" VerticalAlignment="Top" FontSize="10.667" Grid.ColumnSpan="2" Width="180"/></Grid></Window>
Thanks reuven


How to bind a different command to each dynamic button in C#

$
0
0

I have a C# WPF application being built in Visual Studio Community 2015. What I need to do is create buttons dynamically and have each button bound with its own command.

For example button1 will open notepad.exe, button2 will open paint.exe, button3 will open calculator.exe, etc... I can manage this fine with a set amount of buttons that I code in manually and on LeftMouseClick for button1 process.start notepad.exe but that is limited and is bloated.

My understanding is that the ICommand is the way to go but I cannot find enough information on this. Each button must have its own command.


Thank you ahead of time!


Michael J. Hall



StackOverflowException when getting data from property

$
0
0

Hey, i'm trying to get the FirstName property from the Logged class instance, code will make more sense:

The Binding:

<TextBlock Text="{Binding Person.FirstName, Source={StaticResource CurrentlyLogged}}" />

CurrentlyLogged Class Instance:

//Store all User instances logged in
        public ObservableCollection<Logged> People { get; set; }

        private int _selectedItem = 0;
        public int SelectedItem
        {
            get { return _selectedItem; }
            set
            {
                _selectedItem = (value < 0 ? 0 : value);

                RaisePropertyChanged();
                RaisePropertyChanged("Person");
            }
        }

        public PersonList()
        {
            //Initiate new instance of the List
            People = new ObservableCollection<Logged>();
        }

        //Get a user
        public Logged Person
        {
            get
            {
                if (People.Count > 0)
                {
                    //Display the menu
                    Application.Current.Resources["NavigationVisible"] = Visibility.Visible;
                    ((ViewList)Application.Current.Resources["ViewSource"])[1].NavigateExecute();
                    return People[SelectedItem];
                }
                else
                {
                    //Hide the menu if no one is logged in
                    Application.Current.Resources["NavigationVisible"] = Visibility.Collapsed;
                    ((ViewList)Application.Current.Resources["ViewSource"])[0].NavigateExecute();
                }
                return null;
            }
        }

Logged class, nothing fancy here:

public class Logged : Common.NotifyUIBase, IComparable<Logged>
    {
        private string _FirstName;
        public string FirstName
        {
            get { return _FirstName; }
            set { _FirstName = value; RaisePropertyChanged(); }
        }

I can do this fine when loading the content into a list, however i'm struggling to get the binding correct in a single TextBox, as you can see from the code below I navigate down to the FirstName from different controls:

<StackPanel DataContext="{StaticResource CurrentlyLogged}" Style="{StaticResource Users}"><ListView ItemsSource="{Binding People}"
                      SelectedIndex="{Binding SelectedItem}"><ListView.ItemsPanel><ItemsPanelTemplate><StackPanel Orientation="Horizontal" /></ItemsPanelTemplate></ListView.ItemsPanel></ListView><StackPanel Margin="10" DataContext="{Binding Person}"><Ellipse Width="140" Height="140"><Ellipse.Fill><ImageBrush ImageSource="{Binding Image}" Stretch="UniformToFill" /></Ellipse.Fill></Ellipse><WrapPanel HorizontalAlignment="Center"><TextBlock Text="{Binding FirstName}" FontWeight="Bold" />

I have got my Binding completely wrong and I can't figure out how to fix it, my application is getting an exception and producing this error:

An unhandled exception of type 'System.StackOverflowException' occurred in mscorlib.dll

Rotational Busy Indicator

$
0
0

At the moment in my program I have a Window that hosts a ProgressBar control that I am using as an indicator of when my program is performing a task. It is currently a bit outdated for the program, it looks like this;

It isn't terrible but I am looking to implement a more 'modern' busy indicator. What would be perfect is if I could implement something like the indicator below but without the black background, that can still be used by saying window.Show() and window.Close() as I have implemented at the moment;


Is there anything like this I can use or modify to get what I am looking for?

event handling

$
0
0

I have a parent control > grid panel > stakpanel ( added Menu items dropdown) and  dockpanel( user name control)

For parent control I have added MouseMouse event handler, In that I have added a condiotion like  if (e.LeftButton == MouseButtonState.Pressed) then execute a logic.

ParentControl_MouseMove(object sender, MouseEventArgs e)
{

            if (e.LeftButton == MouseButtonState.Pressed)
{
code to be executed...

}

}

Issue is when ever I click menu items or user name controls, Code inside the mouseMove handler is executed, Its
passed in OriginalSource parameters.

I tried handling it by adding PreviewMouseMove handlers in stakpanel ( added Menu items dropdown) and  dockpanel( user name control).
like
Menuheader_PreviewMouseMove(object sender, MouseButtonEventArgs e)
        {
           
                e.Handled = true;
        }
UsernameControl_PreviewMouseMove(object sender, MouseButtonEventArgs e)
        {
           
                e.Handled = true;
        }


 but its not acceptable since it may affect someother code.

How can it be stopped from executing logic in ParentControl_MouseMove event hadler whenever I click menu items or user name controls?

Can any check be done using the OriginalSource passed?

Im not supposed to set e.haddled = true in stakpanel ( added Menu items dropdown) and  dockpanel( user name control) click events.(it may affect some other logics)

Got 2 problems with the DataGrid on this WPF user control

$
0
0

My colleague has written a user control where he's put in a DataGrid to show a collection of data. (I'd rather use a listbox, but we've been instructed to use DataGrids.) The problem with it is (a) it was fixed at 350 pixels/units height, so when the user maximized the window it looked kinda funny; and (b) the vertical scrollbar only appeared with the arrow at the top. You couldn't get to the bottom of the list.

So I started working on trying to improve it. I thought it would be a good idea to put the DataGrid into a layout Grid control, which is what I did. But now something else has gone wrong and I haven't a clue as to what. When running it the user control comes up with the stack panel at the top above the DataGrid. But the DataGrid doesn't show up at all and I can't interact with the user control at all. Even clicking on the close button to the window hosting the user control with the DataGrid in it, is useless. It does nothing.

Why am I seeing this behavior? Here's the XAML:

<UserControl x:Class="CoreFramework.View.CustomerView"
       xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:uc="clr-namespace:CoreFramework.UserControls"
        xmlns:converter="clr-namespace:CoreFramework.ValueConverters"
        xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"
        xmlns:cmd="clr-namespace:GalaSoft.MvvmLight.Command;assembly=GalaSoft.MvvmLight.Platform"
        xmlns:ignore="http://www.galasoft.ch/ignore"
        mc:Ignorable="d ignore" Loaded="UserControl_Loaded"><UserControl.Resources><converter:RequiredFieldConverter x:Key="requiredConverter" /></UserControl.Resources><Grid><Grid.RowDefinitions><RowDefinition Height="auto"/><RowDefinition Height="*" /></Grid.RowDefinitions><StackPanel MinWidth="200"><Grid><Grid.ColumnDefinitions><ColumnDefinition Width="8*" /><ColumnDefinition Width="auto" /></Grid.ColumnDefinitions><TextBlock Text="{Binding TableHeader, UpdateSourceTrigger=PropertyChanged}"  Style="{StaticResource Heading2}" /><Menu Grid.Column="1" FontSize="10.667" Background="{x:Null}"><MenuItem Header="SETTINGS" Background="{x:Null}" Foreground="#FF706C6C" Command="{Binding ViewSettingsCommand}" Click="MenuItem_Click"/><MenuItem Header="|" Background="{x:Null}" Foreground="#FFD1CFCF" IsEnabled="False" IsHitTestVisible="False"  /><MenuItem Header="HELP" Background="{x:Null}" Foreground="#FF706C6C"  Command="{Binding ViewHelpCommand}" /></Menu></Grid><uc:CoreToolbar /></StackPanel><TabControl x:Name="ViewPort"
                    Margin="0,0,0,0"
                    BorderThickness="0"
                    Grid.Row="1"
                    SelectedIndex="{Binding ViewIndex,  Mode=OneWay,UpdateSourceTrigger=PropertyChanged, IsAsync=True}" Background="Transparent" ><TabControl.Resources><Style TargetType="TabItem"><Setter Property="Template" ><Setter.Value><ControlTemplate TargetType="TabItem" /></Setter.Value></Setter></Style></TabControl.Resources><TabItem Header="Summary"><Grid><Grid.RowDefinitions><RowDefinition MinHeight="350" /></Grid.RowDefinitions><DataGrid Name="dataGrid"
                          ItemsSource="{Binding Rows}"
                          SelectedItem="{Binding SelectedRow, UpdateSourceTrigger=PropertyChanged}"
                          IsReadOnly="True"
                          VerticalScrollBarVisibility="Visible"
                          IsSynchronizedWithCurrentItem="True" AutoGeneratingColumn="dataGrid_AutoGeneratingColumn"><DataGrid.ContextMenu><ContextMenu><MenuItem Header="Show All" Icon="{StaticResource ShowAllImage}" Command="{Binding ShowAllCommand}"/><MenuItem Header="Omit Set" Icon="{StaticResource OmitImage}" Command="{Binding OmitSetCommand}"/><MenuItem Header="Establish Set" Icon="{StaticResource EstablishImage}" Command="{Binding EstablishSetCommand}"/><MenuItem Header="Recall Set" Icon="{StaticResource RecallImage}" Command="{Binding RecallSetCommand}"/><MenuItem Header="Merge Sets" Icon="{StaticResource MergeImage}" Command="{Binding MergeSetCommand}"/></ContextMenu></DataGrid.ContextMenu><i:Interaction.Triggers><i:EventTrigger EventName="MouseDoubleClick"><i:InvokeCommandAction Command="{Binding EditItemCommand}" /></i:EventTrigger><i:EventTrigger EventName="SelectionChanged"><cmd:EventToCommand Command="{Binding SelectionChangedEventCommand}"
                                                PassEventArgsToCommand="True"
                                                CommandParameter="{Binding SelectedItems, ElementName=dataGrid}"  /></i:EventTrigger></i:Interaction.Triggers></DataGrid></Grid></TabItem><TabItem Header="Detail"><Grid Style="{StaticResource ContentTop}"><ScrollViewer><StackPanel MinWidth="200"><StackPanel x:Name="Column1" Orientation="Vertical" Grid.Column="0"><StackPanel.Resources><Style TargetType="{x:Type TextBox}"><Setter Property="Margin" Value="3" /><Setter Property="HorizontalAlignment" Value="Left"/></Style><Style TargetType="{x:Type TextBlock}"><Setter Property="Margin" Value="3" /><Setter Property="Height" Value="23" /><Setter Property="FontWeight" Value="Bold" /><Setter Property="VerticalAlignment" Value="Center" /></Style></StackPanel.Resources><Grid HorizontalAlignment="Left" ><Grid.ColumnDefinitions><ColumnDefinition Width="auto" /><ColumnDefinition Width="*"/></Grid.ColumnDefinitions><Grid.RowDefinitions><RowDefinition Height="auto" /></Grid.RowDefinitions><StackPanel Orientation="Vertical" Margin="0,4,0,0"><TextBlock Text="ID " TextDecorations="{Binding Customer.ID, Converter={StaticResource requiredConverter}, ConverterParameter=Customer|ID}"/><TextBlock Text="Extension " TextDecorations="{Binding Customer.Extension, Converter={StaticResource requiredConverter}, ConverterParameter=Customer|Extension}"/><TextBlock Text="Fax " TextDecorations="{Binding Customer.Fax, Converter={StaticResource requiredConverter}, ConverterParameter=Customer|Fax}"/><TextBlock Text="Phone " TextDecorations="{Binding Customer.Phone, Converter={StaticResource requiredConverter}, ConverterParameter=Customer|Phone}"/><TextBlock Text="Shipping Address " TextDecorations="{Binding Customer.Shipping_Addr1, Converter={StaticResource requiredConverter}, ConverterParameter=Customer|Shipping_Addr1}"/><TextBlock Text=" " /><TextBlock Text="Shipping City " TextDecorations="{Binding Customer.Shipping_City, Converter={StaticResource requiredConverter}, ConverterParameter=Customer|Shipping_City}" /><TextBlock Text="Shipping State " TextDecorations="{Binding Customer.Shipping_State, Converter={StaticResource requiredConverter}, ConverterParameter=Customer|Shipping_State}" /><TextBlock Text="Shipping Zipcode " TextDecorations="{Binding Customer.Billing_Zip, Converter={StaticResource requiredConverter}, ConverterParameter=Customer|Billing_Zip}" /><TextBlock Text="Billing Address " TextDecorations="{Binding Customer.Billing_Addr1, Converter={StaticResource requiredConverter}, ConverterParameter=Customer|Billing_Addr1}" /><TextBlock Text=" " /><TextBlock Text="Billing City " TextDecorations="{Binding Customer.Billing_City, Converter={StaticResource requiredConverter}, ConverterParameter=Customer|Billing_City}"/><TextBlock Text="Billing State " TextDecorations="{Binding Customer.Billing_State, Converter={StaticResource requiredConverter}, ConverterParameter=Customer|Billing_State}"/><TextBlock Text="Billing Zipcode " TextDecorations="{Binding Customer.Billing_Zip, Converter={StaticResource requiredConverter}, ConverterParameter=Customer|Billing_Zip}"/><TextBlock Text="Comments " TextDecorations="{Binding Customer.Comments, Converter={StaticResource requiredConverter}, ConverterParameter=Customer|Comments}"/><TextBlock Text="Company Name " TextDecorations="{Binding Customer.Company_Name, Converter={StaticResource requiredConverter}, ConverterParameter=Customer|Company_Name}" /><TextBlock Text="Contact Name " TextDecorations="{Binding Customer.Contact_Name, Converter={StaticResource requiredConverter}, ConverterParameter=Customer|Contact_Name}"/><TextBlock Text="Email " TextDecorations="{Binding Customer.Email, Converter={StaticResource requiredConverter}, ConverterParameter=Customer|Email}"/></StackPanel><StackPanel Orientation="Vertical" Grid.Column="1" HorizontalAlignment="Left"><TextBox x:Name="txtID" Width="150" Text="{Binding Path=Customer.ID}" IsReadOnly="True"  /><TextBox x:Name="txtExtension" Width="250" Text="{Binding Path=Customer.Extension}"  /><TextBox x:Name="txtFax" Width="250" Text="{Binding Path=Customer.Fax}"  /><TextBox x:Name="txtPhone" Width="250" Text="{Binding Path=Customer.Phone}"  /><TextBox x:Name="txtShipping_Addr1" Width="250" Text="{Binding Path=Customer.Shipping_Addr1}"  /><TextBox x:Name="txtShipping_Addr2" Width="250" Text="{Binding Path=Customer.Shipping_Addr2}"  /><TextBox x:Name="txtShipping_City" Width="250" Text="{Binding Path=Customer.Shipping_City}"  /><TextBox x:Name="txtShipping_State" Width="250" Text="{Binding Path=Customer.Shipping_State}"  /><TextBox x:Name="txtShipping_Zip" Width="250" Text="{Binding Path=Customer.Shipping_Zip}"  /><TextBox x:Name="txtBilling_Addr1" Width="250" Text="{Binding Path=Customer.Billing_Addr1}"  /><TextBox x:Name="txtBilling_Addr2" Width="250" Text="{Binding Path=Customer.Billing_Addr2}"  /><TextBox x:Name="txtBilling_City" Width="250" Text="{Binding Path=Customer.Billing_City}"  /><TextBox x:Name="txtBilling_State" Width="250" Text="{Binding Path=Customer.Billing_State}"  /><TextBox x:Name="txtBilling_Zip" Width="250" Text="{Binding Path=Customer.Billing_Zip}"  /><TextBox x:Name="txtComments" Width="400" Text="{Binding Path=Customer.Comments}"  /><TextBox x:Name="txtCompany_Name" Width="250" Text="{Binding Path=Customer.Company_Name}"  /><TextBox x:Name="txtContact_Name" Width="250" Text="{Binding Path=Customer.Contact_Name}"  /><TextBox x:Name="txtEmail" Width="250" Text="{Binding Path=Customer.Email}"  /></StackPanel></Grid></StackPanel></StackPanel></ScrollViewer></Grid></TabItem></TabControl></Grid></UserControl>


Rod

CollectionContainer does not support RelativeSource

$
0
0
Hi all

I've discovered that I cannot assing a relative binding to a CollectionContainer.Collection dependency property:

Code Snippet

    <ListBox>
      <ListBox.ItemsSource>
        <CompositeCollection>

// binding works

          <TextBox Text="{Binding RelativeSource={RelativeSource AncestorType=local:Window1},Path=Number2,Mode=OneWay}"/>

// binding fails ("cannot find source ...")

          <CollectionContainer Collection="{Binding RelativeSource={RelativeSource AncestorType=local:Window1},Path=Numbers3,Mode=OneWay}"/>
        </CompositeCollection>
      </ListBox.ItemsSource>
    </ListBox>



I guess that this behaviour is because CollectionContainer does not derive from FrameworkElement, therefore the CollectionContainer not being part of the visual tree.

Are there any workarounds, other than writing a Wrapper (which is what I intend to do)?

Kuno

Header style of data grid is not standardize when the data is group by expander

$
0
0

I have a standard style for my data grid header.

When there is data in the data grid, and my data is group by expander, a new column is auto generated for expander and the style of the newly created column is not following my data grid style. Meaning the first column header is in grey colour, while the rest of the column header is blue in colour (as follow my style).

Here is my codes:

DataGrid

<DataGridScrollViewer.HorizontalScrollBarVisibility="Auto"Name="dataGridResult"Grid.Row="1"RowHeight="20"ItemsSource="{Binding ResultList, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"BorderBrush="White"IsReadOnly="True"VirtualizingPanel.IsVirtualizingWhenGrouping="True"Margin="15"Style="{StaticResource DataGridStyle}"GridLinesVisibility="None"><DataGrid.Columns><DataGridTextColumnWidth="180"Header="Column1"Binding="{Binding RunNo}"/><DataGridTextColumnWidth="Auto"Header="Column2"Binding="{Binding TestProgramVersion}"/><DataGridTextColumnWidth="150"Header="Column3"Binding="{Binding StartTestTime}"/><DataGridTextColumnWidth="150"Header="Column4"Binding="{Binding EndTestTime}"/></DataGrid.Columns><DataGrid.GroupStyle><GroupStyle><GroupStyle.ContainerStyle><StyleTargetType="{x:Type GroupItem}"><Setter Property="Template"><Setter.Value><ControlTemplate><Expander x:Name="MyExpander" IsExpanded="True"><Expander.Header><StackPanel Orientation="Horizontal"><TextBlock x:Name="MyExpanderHeader" Text="{Binding Name}" FontWeight="Bold" VerticalAlignment="Bottom"/></StackPanel></Expander.Header><ItemsPresenter Margin="20,0,0,0"/></Expander></ControlTemplate></Setter.Value></Setter></Style></GroupStyle.ContainerStyle></GroupStyle></DataGrid.GroupStyle></DataGrid>

Style

<Stylex:Key="DataGridStyle"TargetType="DataGrid"><Setter Property="ColumnHeaderStyle" Value="{StaticResource DataGridColumnHeaderStyle}"/></Style><Stylex:Key="DataGridColumnHeaderStyle"TargetType="{x:Type DataGridColumnHeader}"><Setter Property="Foreground" Value="White"/><Setter Property="Background" Value="#FF048EC0"/><Setter Property="Padding" Value="5,0,5,0"/><Setter Property="HorizontalContentAlignment" Value="Left"/></Style>



Get the Highlighted text in an editable combobox

$
0
0
I need to get the highlighted text ( if we select the part of the string in the text box inside a combobox) how can we get this text in the viewmodel?

Datatable row header

$
0
0

   

    public partial class MainWindow : Window
    {
        DataTable dtSquad = new DataTable();
        public MainWindow()
        {
            InitializeComponent();

           
        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            for (int i = 0; i < 25; i++)
            {
                dtSquad.Columns.Add(new DataColumn(i.ToString()+"column"));
            }

            DataRow drSquad;

            for (int i = 0; i <= 20; i++)
            {
                drSquad = dtSquad.NewRow();
                dtSquad.Rows.Add(drSquad);

                drSquad[0] = i.ToString() + "row";
            }

            dgdSquadResultBoard.ItemsSource = dtSquad.DefaultView;
        }
    }

When youmove thescroll
Column Headerwillnot move.
ButRow Headermoves.

I would like todo not moveRow Header.
Iwould like to createa row headerascolumn header.

Pleaseanswer.

how to convert a xml string to a treeview directly using some dll..

$
0
0
how to convert a  xml  string to a treeview  directly using some dll..

How to keep a FrameworkElement at the middle during animation?

$
0
0
 

I try to make a toolBar that is on the Top Center of the Window.

The width of the toolbar may change during the runtime. I want to trigger the width with the help of VisualStates (which seems very practical to me) and Animations (Using Key Frames).

To simplify the issue as much as possible, I put inside a window a DockPanel with inside : 

 1. a StackPanel containing two buttons (to switch from one visual state to the other one).
 2. a Button that will be animated by the two VisualStates added to its ControlTemplate.

Here is a screenshot of this window

http://i.stack.imgur.com/7LvJR.png

The Xaml Code :

<Window xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:is="http://schemas.microsoft.com/expression/2010/interactions"
        xmlns:Themes="clr-namespace:Microsoft.Windows.Themes;assembly=PresentationFramework.Aero" x:Class="DockPanelIssue.MainWindow"
        Background="LightYellow"
        Title="MainWindow" Height="200" Width="400"><DockPanel Background="Blue" HorizontalAlignment="Center" VerticalAlignment="Top"><StackPanel Margin="5" DockPanel.Dock="Bottom" Background="Orange" Orientation="Horizontal" HorizontalAlignment="Center"><Button Margin="5" Click="Show_Click" Content="Show"/><Button Margin="5" Click="Hide_Click" Content="Hide"/></StackPanel><Button Margin="5" x:Name="theButton" Background="Yellow" HorizontalAlignment="Center" VerticalAlignment="Center"><Button.Template><ControlTemplate TargetType="{x:Type Button}"><ContentControl><VisualStateManager.CustomVisualStateManager><is:ExtendedVisualStateManager /></VisualStateManager.CustomVisualStateManager><VisualStateManager.VisualStateGroups><VisualStateGroup is:ExtendedVisualStateManager.UseFluidLayout="True"><VisualStateGroup.Transitions><VisualTransition GeneratedDuration="0:0:3"/></VisualStateGroup.Transitions><VisualState x:Name="StateHide"><Storyboard><DoubleAnimationUsingKeyFrames Storyboard.TargetProperty="(FrameworkElement.Width)" Storyboard.TargetName="Chrome"><DoubleKeyFrameCollection><LinearDoubleKeyFrame KeyTime="0%" Value="200"/><LinearDoubleKeyFrame KeyTime="50%" Value="150"/><LinearDoubleKeyFrame KeyTime="100%" Value="100"/></DoubleKeyFrameCollection></DoubleAnimationUsingKeyFrames></Storyboard></VisualState><VisualState x:Name="StateShow"><Storyboard><DoubleAnimationUsingKeyFrames Storyboard.TargetProperty="(FrameworkElement.Width)" Storyboard.TargetName="Chrome"><DoubleKeyFrameCollection><LinearDoubleKeyFrame KeyTime="0%" Value="100"/><LinearDoubleKeyFrame KeyTime="50%" Value="150"/><LinearDoubleKeyFrame KeyTime="100%" Value="200"/></DoubleKeyFrameCollection></DoubleAnimationUsingKeyFrames></Storyboard></VisualState></VisualStateGroup></VisualStateManager.VisualStateGroups><Border x:Name="Chrome" BorderBrush="{TemplateBinding BorderBrush}" Background="{TemplateBinding Background}" SnapsToDevicePixels="true"><ContentPresenter HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}" Margin="{TemplateBinding Padding}" RecognizesAccessKey="True" SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}" VerticalAlignment="{TemplateBinding VerticalContentAlignment}"/></Border></ContentControl></ControlTemplate></Button.Template>
            Animated Button</Button></DockPanel></Window>


and the code behind to trigger the VisualStates :

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

        private void Hide_Click(object sender, RoutedEventArgs e)
        {
            ExtendedVisualStateManager.GoToState(theButton, "StateHide", true);
        }

        private void Show_Click(object sender, RoutedEventArgs e)
        {
            ExtendedVisualStateManager.GoToState(theButton, "StateShow", true);
        }
    }




What we were expecting is that the AnimatedButton (the yellow one) increases his width over 3 seconds, ( and stay in the middle ! ). But the result is :

 1. Actually , the width is small, we click on the Hide Button.
 2. Immediately, the Animated Button is shifted on the Left.
 3. the Animated Button is still on the Left, width is growing.
 4. Just before the end of the animation, the Animated Button is still on the Left.
 5. The Animation is finished, the Animated Button is now taller and it is back on the middle (Phew !)

The beginning and the end is what we want, but the transition ( 2, 3, 4) is not correct.

Here is a picture with the screenshots from step 1 to 5, and drawings that illustrate what we want :

http://i.stack.imgur.com/6WYFq.png

How to achieve this ?

They are some other points that I don't really understand :

1. Why when i click on hide, the button is growing ( I Expected it shrinking )
2. Why is one of the two animations not playing the transition.
3. Why does the Blue DockPanel takes so much width and so less Height during the Animation (seems that the Orange stackPanel is calculated to be docked at the right during animation instead of Bottom) ?

Windows 10 Windows Resizing Problem, Windows Forms and WPF

$
0
0

Hello,

we have a Windows Forms Application with Element host to have some WPF controls in it.

Everything works in Windows 7 but we have problems in Windows 8 and Windows 10.

The Windows Forms application works perfectly until the application opens a windows with a WPF Controls, after this the forms are resized the fonts are resized and everything becomes impossible to work.

Any solution?

thank you so much

You could be our Fabulous February WPF Guru!

$
0
0

Fabulous February is here at last!

This is the month some of the greatest names in TechNet Wiki history will step forth and give us knowledge!

That's YOU by the way!

Drop us a little ray of sun, a few lines of love, or virtual valentine!

Your revelations could enrich so many more if you copied it for posterity into the wiki of wisdom

We need heroes! We need YOU! Join us and grow your reputation amongst some of the greats of the community!

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.

 

January's entries are now being judged, but below are December's mighty winners and contenders!

Guru Award BizTalk Technical Guru - December 2015  

Gold Award Winner

Peter LindgrenBizTalk: Create SSO Bindings Without Joining Active Directory (AD) DomainSK: "Very good article"
SW: "Pragmatic Approach in Development Environment"

Silver Award Winner

Steef-Jan WiggersBizTalk Server : Call external code in an orchestrationSW: "Good explanation and demonstration when to use/call external code in an orchestration."
SK: "Great work here"

Guru Award Forefront Identity Manager Technical Guru - December 2015  

Gold Award Winner

Wim BeckFIM2010: Outbound System Scoping Filter SyntaxSøren Granfeldt: "The best"
PG: "Nice solution, very helpful"

Silver Award Winner

Jeff IngallsHow to Use PowerShell to Create a CSV of FIM/MIM Metaverse ConnectionsPG: "Nice solution, well documented, very helpful"
Søren Granfeldt: "Very interesting read"

Guru Award Microsoft Azure Technical Guru - December 2015  

Gold Award Winner

XAML guyIoT Suite - Under The Hood - Remote MonitoringAS: "Very good article. Just made me play around with the stuff."
JH: "Good explanation of the remote monitoring sample of the IoT Suite. More articles about the IoT Suite are more than appreciated."

Silver Award Winner

Sajid Ali KhanJumpStart into Big Data with HDInsightJH: "Nice article to get started with HDInsight. Lots of easy to follow graphics."
AS: "Nice post. But somehow I really wanted to jump start with Big Data without having to deal with Hadoop :)"

Bronze Award Winner

Ken CenerelliAzure Infographics and Visio TemplatesAN: "Just listing infographics does not add any value for the users. One can just stop by: https://azure.microsoft.com/en-us/documentation/infographics/ and review / download all"
JH: "Good collection of the infographics available for Azure."

Guru Award Miscellaneous Technical Guru - December 2015  

Gold Award Winner

Ken CenerelliCommand Prompt improvements in Windows 10Richard Mueller: "Very interesting and useful information. Well written and explained."

Silver Award Winner

SYEDSHANUASP.Net Web Photo Editing Tool Using HTML 5Richard Mueller: "Lots of well commented code. Good images. Good use of Wiki guidelines. We could use an "Other Resources" section."

Bronze Award Winner

Hussain Shahbaz KhawajaVisual Studio Community for Java DevelopersRichard Mueller: "Good images. We could use links and references."

Guru Award SharePoint 2010 / 2013 Technical Guru - December 2015  

Gold Award Winner

Danish IslamSharePoint: Filter Dropdown values on List InfoPath form based on Current UserRichard Mueller: "Good use of Wiki guidelines. Great images. The "See Also" is good, but because the links are not Wikis, it should be "Other Resources"."

Silver Award Winner

Jesper ArneckeSharePoint 2013 - Workflow Manager – Scripted InstallationRichard Mueller: "Lots of code. References are good, but we could use a "See Also" section."

Bronze Award Winner

Danish IslamSharePoint: Hiding or Ordering Fields on Default List FormsRichard Mueller: "Great use of Wiki guidelines. We can use some references."

Guru Award Small Basic Technical Guru - December 2015  

Gold Award Winner

SYEDSHANUMicrosoft Small Basic: Painting Tool Using Graphics WindowRZ: "This is very nicely done! Fantastic tool for painting and illustrating the drawing capabilities of SmallBasic"

Silver Award Winner

Ed Price - MSFTSmall Basic Sample: Leap Year CheckerRZ: "Leap year calculation is always interesting -- the rules are always just a bit more complicated than you expect :)"

Guru Award SQL BI and Power BI Technical Guru - December 2015  

Gold Award Winner

Greg Deckler (Quick Solutions)Merge Query with MPT: "Greg, nice tip. It's good to see how simple M script techniques like this can supercede the out-of-the-box script generated by the UI tool. I'll use this often."

Guru Award SQL Server General and Database Engine Technical Guru - December 2015  

Gold Award Winner

Ronen ArielySQLCLR: Percentage User-Defined Aggregate FunctionsDurval Ramos: "This article is interesting, but needs more details to demonstrate how to create and use an assembly .Net on SQL Server"

Guru Award System Center Technical Guru - December 2015  

Gold Award Winner

C Sharp ConnerSolution - Correctly restoring Data Warehouse and Registering to SCSM when Cube Process Jobs have gone BadAB: "Nice solution"
Nicolas Bonnet: "Thank you for posting this C Sharp Corner :)"

Silver Award Winner

Adin ErmieService Manager 2012 R2 Installation Fails To Identify SQL Server Instance, and Throws ‘Access Denied’ ErrorNicolas Bonnet: "Nice tip Adin, trhanks"
AB: "Useful read!"

Guru Award Transact-SQL Technical Guru - December 2015  

Gold Award Winner

Naomi NT-SQL: Finding Difference in Columns in the TableDurval Ramos: "This article provides an useful solution to compare values. A very well written and good article that have "Conclusion" to the reader"
Richard Mueller: "Great article. Good use of Wiki guidelines and good code examples."
Samuel Lester: "Outstanding solution! Thanks again for the great depth of your submissions! Job well done!"

Silver Award Winner

Natig GurbanovHow to find incorrect datetime data from "Char" format columnDurval Ramos: "An interesting article about how to use ISDATE function "
Richard Mueller: "Grammar needs work and references would help."
Samuel Lester: "Another good tip, thanks again"

Bronze Award Winner

Natig GurbanovSql Server:Unusual String FunctionsRichard Mueller: "A good effort, but grammar needs work and we could use more explanation."
Samuel Lester: "Fun tip, thanks for covering this rarely discussed function"
Durval Ramos: "Nice, could do with some more work"

Guru Award Universal Windows Apps Technical Guru - December 2015  

Gold Award Winner

Umer QureshiHow to create and use custom controlJH: "Nice article. Love the animated pictures."

Silver Award Winner

Sajid Ali KhanJumpStart With Data Binding in UWPJH: "Very informative article about data binding. Unfortunately some of the pictures are missing."

Bronze Award Winner

Umer QureshiIntroduction To Data Binding Using Model ClassJH: "Good example of one of the greatest features of XAML."

Guru Award Visual Basic Technical Guru - December 2015  

Gold Award Winner

tommytwotrainSpace Invaders game using a DataTable and DataGridViewAnthony D. Green: "Bonus points for being fun. It's also well presented and informative."
AN: A great fun article, well laid out too"
Richard Mueller: "A very well written article. Lots of code and good references."
Carmelo La Monica: "Very nice work, is very good to see a game with Datagrid. Congrats for work and vb net code."

Silver Award Winner

SYEDSHANUExternal Program Text Read using VB.NETCarmelo La Monica: "Nice article, great animate images and vb net code."
AN: "Very nice article, lots to read and love"
Anthony D. Green: "Well structured but needs some proof reading. It's an informative example of using the Win32 API through P/Invoke but lacks sufficient motivation for the example."
Richard Mueller: "Grammar needs work and we could use references."

Bronze Award Winner

.paul.InputDialog DemoRichard Mueller: "Great examples and code."
Carmelo La Monica: "Great work, very interesting sample and code. Congrats."
ANThe article is too short/simple. It re-implements funtionality available in the platform without demonstrating clear benefit. It's more of a code sample than an article.

Guru Award Visual C# Technical Guru - December 2015  

Gold Award Winner

Anil KumarC# Delegate – a silent hero behind modern programmingJaliya Udagedara: "Explains one of the most important types in .NET Framework. It would have been good if explained with more sample code."
Carmelo La Monica: "Fantastic topic, great code, congrats!"

Silver Award Winner

Qasim ChaudhryHow To Customize Identity in ASP.NET MVC5Jaliya Udagedara: "Good! Step by step guide to customize ASP.NET Identity."
Carmelo La Monica: "I'm not expert of AspNet, but this article is very useful and detailed in all parts!"

Bronze Award Winner

SYEDSHANUSPC CP and Cpk Chart in C# Windows FormsCarmelo La Monica: "Fantastic, i mean is similar to tool for debug, great work."
Jaliya Udagedara: "Needs some explanations to the code."

Guru Award Wiki and Portals Technical Guru - December 2015  

Gold Award Winner

Andy ONeillTechNet Guru Iconography SuggestionsRichard Mueller: "What fun! Lots of good ideas here. Gets me thinking."

Guru Award Windows PowerShell Technical Guru - December 2015  

Gold Award Winner

Ken CenerelliList Services With PowerShellRichard Mueller: "Well written article. The "See Also" section should only include Wiki articles, so those links could go in the "References" section."

Guru Award Windows Presentation Foundation (WPF) Technical Guru - December 2015  

Gold Award Winner

Andy ONeillSeasons GreetingsPeter Laker: "Yey for the seasonal article!"

Silver Award Winner

Umer QureshiDifference between Grid and StackPanelPeter Laker: "Nice explanation, thanks Umer"

 

Thanks in advance!
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!

User control not showing in designer or final application

$
0
0

Hello,

I created a WPF project in VS 2010 express edition with a main window and a user control. Both have their own XAML and code behind CS files.

The user control (consists of a grid and a button) shows up in the toolbox and is offered by intellisense so I guess it's legally included. If I put the user control on the window per drag and drop, it gets shown, but it seems to have the size of 1 pixel. If I increase its size (either by mouse in the designer or via XAML), the (larger) borders of the user control get shown in the designer, but the context of it is blank - no button is visible.

When I check the visibility property at runtime, it is set to true. So it should be visible. However I don't see the user control and the mouse cursor does not change to hand as it should. In case I change the background colour of the user control upon the loaded event, suddenly I see the user control, the hand cursor works, but still no button is visible.

Here is the XAML of the user control:

<UserControl x:Class="nsSomething.ViewA"
             x:Name="ViewAControl"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"><Grid Name="other"><Grid.ColumnDefinitions><ColumnDefinition Width="300"/></Grid.ColumnDefinitions><Grid.RowDefinitions><RowDefinition Height="300"/></Grid.RowDefinitions><Button Name="TestButton" Content="My Button" Height="23" HorizontalAlignment="Left" VerticalAlignment="Top" Width="75" /></Grid></UserControl>

And here is the XAML for the window:

<Window x:Class="nsSomething.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:st="clr-namespace:nsSomething"
        Loaded="MainWindowOnLoaded"
        Closing="MainWindowOnClosing"
        Title="Test" Height="1050" Width="1680" ResizeMode="NoResize" WindowStyle="None" Topmost="True" WindowStartupLocation="CenterScreen" Background="White" WindowState="Maximized"><Grid Name="LayoutRoot" ShowGridLines="True"><Grid.ColumnDefinitions><ColumnDefinition /><ColumnDefinition /></Grid.ColumnDefinitions><Grid.RowDefinitions><RowDefinition /><RowDefinition /></Grid.RowDefinitions><st:ViewA x:Name="view1" Width="200" Height="200" Grid.Column="0" Grid.Row="0" VerticalAlignment="Top" Cursor="Hand" HorizontalAlignment="Left" Loaded="view1_Loaded" /><Button Name="button1" Grid.Column="0" Grid.Row="1" Content="Button" Height="23" HorizontalAlignment="Left" VerticalAlignment="Top" Width="75" /></Grid></Window>

Note that view1_Loaded is only used to change the background colour for the test described above.

Also please note, that I changed the variable names, but I think it should work this way as well.

As all my research showed that I seem to be the only one having such an issue, I guess I must be doing something terribly wrong...

Any help is appreciated! Thanks in advance!



WPF Dead or Not?

$
0
0

We've seen all the postings about WPF being Dead.  We heard from MSFT it was not, and they were starting to work on it again.  It's now about two years later and we see next to nothing regarding progress in WPF.   WPF was cutting edge technology and MVVM was "borrowed" by Angular to do client side binding very similar to what we already did with MVVM.  C'mon MSFT "Get Going"...  You're inaction is speaking loudly to us WPF adopters.

Should MSFT open source WPF being that they are unwilling to move it forward? 

Or should MSFT put a real plan together and let us know what's going on.  

Or is MSFT saying to us Typescript is the future and everything should be hosted in a browser which they don't have for WPF (without airspace issues).  

Here's a suggestion for MSFT, give us real browser so that we want and choose to embed your browser rather than CEF (Chrome Embedded Framework).  

Linq - Group items and then pull the first item from each group

$
0
0

Hello,

I have a program that reads in several XML files and creates a list of objects.

The object contains three properties:  Area, Item, Description.

Each area contains multiple items and each item contains multiple descriptions as follows:

AREA       ITEM   DESCRIPTION

area 11 Text 1 - 1

area 11 Text 2 - 1

area 1Text 3 - 1

area 12 Text 1 - 2

area 1 Text 2 - 2

area 23 Text 1 - 3

area 2Text 2 - 3

I would like to be able to write a single LINQ statement that pulls out the item and first descripton (Text 1) for each Item in a given area.

The result for area 1 above would be:

1  Text 1 - 1

2Text 1 - 2

 

This is my starting point.

              List<rowObject> itemsInArea = (from rowObject in listOfRowObjects

                                               where rowObject.area == area 1

                                               select rowObject).ToList();

It just do not know how to craft the balance of the query.

Any suggestions would be greatly appreciated.

 

Chris

 

Set the caret position in the Combo Text Box

$
0
0

Currently when the text is entered in the combobox and then select a part of it and hit virtual Backspace key it removes the selected string. But the cursor position moves to the end of the text. I am trying to handle this using textbox size changed event in the derived combobox. There is a cast exception at _newTextSize = Convert.ToInt32(e.NewSize);  Unable to cast object of type 'System.Windows.Size' to type 'System.IConvertible'.

namespace xxx.Presentation
{
    public class MyComboBox : ComboBox
    {
        TextBox _textBox;
        int _txtLength;
        int _caretIndex;
        int _caretIndexOld;
        int _caretPositionChangeSize;
        int _oldTextSize;
        int _newTextSize;

        public string SelectedText
        {
            get { return (string)GetValue(SelectedTextProperty); }
            set { SetValue(SelectedTextProperty, value); }
        }

        public string CaretIndex
        {
            get { return (string)GetValue(CaretIndexProperty); }
            set { SetValue(CaretIndexProperty, value); }
        }

        public static readonly DependencyProperty SelectedTextProperty =
            DependencyProperty.Register("SelectedText", typeof(string), typeof(MyComboBox), new PropertyMetadata(string.Empty));

        public static readonly DependencyProperty CaretIndexProperty =
            DependencyProperty.Register("CaretIndex", typeof(int), typeof(MyComboBox), new PropertyMetadata(0));
        public override void OnApplyTemplate()
        {
            base.OnApplyTemplate();
            _textBox = Template.FindName("PART_EditableTextBox", this) as TextBox;
            if (_textBox != null)
            {
                _textBox.GotKeyboardFocus += _textBox_GotFocus;
                _textBox.SelectionChanged +=_textBox_SelectionChanged;
                _textBox.SizeChanged +=_textBox_SizeChanged;
                //_textBox.Select(_textBox.Text.Length, 0);
            }
        }

        private void _textBox_SizeChanged(object sender, SizeChangedEventArgs e)
        {
            if (null != e.PreviousSize && null != e.PreviousSize)
            {
                _newTextSize = Convert.ToInt32(e.NewSize);
                _oldTextSize = Convert.ToInt32(e.PreviousSize);
                _caretPositionChangeSize = _oldTextSize - _newTextSize;
                _textBox.CaretIndex = _oldTextSize - _caretPositionChangeSize;
            }
        }

        private void _textBox_SelectionChanged(object sender, System.Windows.RoutedEventArgs e)
        {
            if (_textBox.Text == null || _textBox.Text.Length == 0)
            {
                SetCurrentValue(SelectedTextProperty, string.Empty);
            }
            else
            {
                SetCurrentValue(SelectedTextProperty, _textBox.SelectedText);
            }
        }

        private void _textBox_GotFocus(object sender, System.Windows.RoutedEventArgs e)
        {
//            _textBox.Select(_textBox.Text.Length, 0);
        }

    }
}


wpf slider thumbnail preview video

$
0
0

Hello,
I need advice on how to create WPF video preview when hovering mission on slidebar.
As in Figure

Image1   Image2


I was able to create only a preview time.

So when I attach source code.

SimpleMediaPlayer

Thanks so much for wheeled advice.




Update Value when Internet Connection changes and External Device is connected

$
0
0

Another question on the best way to do something, I want my application to constantly check that there is an internet connection, and then if there is a change then update a Resource (Boolean) for use in other places in the application, mainly to switch to an online database if it's available. 

For this I have found some code which does afew different checks, one of the main checks to see if there is actually a connection, and it's not just seeing the local area connection, is to check packets sent and received. 

But how would you suggesting doing this so it's following MVVM, but I don't just one check on startup, need it to update on it's own if the connection is lost for example.

And secondly, I need the same kind of thing but for External Devices, such as Pen Drives and SD Cards (most machines with this application have an SD Card reader). I need it to update on it's own if something is inserted, and then populate a Resource (ObservableCollection) of connected devices. 

Viewing all 18858 articles
Browse latest View live


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