lundi 11 mai 2015

ItemsControl (WrapPanel) Grouping should split GroupItems

I have a ItemsControl with a WrapPanel as ItemsHost and multiple Groupings. Got this going so far with the following Templates:

<GroupStyle.ContainerStyle>
   <Style TargetType="GroupItem">
      <Setter Property="Template">
         <Setter.Value>
            <ControlTemplate TargetType="GroupItem">
               <Grid>
                  <Grid.RowDefinitions>
                     <RowDefinition Height="Auto" />
                     <RowDefinition Height="*" />
                  </Grid.RowDefinitions>
                  <ContentPresenter Grid.Row="0" x:Name="PART_Header" Content="{TemplateBinding Content}" />
                  <ItemsPresenter Grid.Row="1" />
               </Grid>
            </ControlTemplate> 
         </Setter.Value>
      </Setter>
   </Style>
</GroupStyle.ContainerStyle>
<GroupStyle.Panel>
   <ItemsPanelTemplate>
      <WrapPanel IsItemsHost="True" Orientation="Vertical" />
   </ItemsPanelTemplate>
</GroupStyle.Panel>

Now I have the Problem that every Group does start a new Column why I want it to Continue right under the last GroupItem and Wrap in the Middle of the GroupItem instead of at the beginning.

It should look like the Windows 8 Apps overview (not the start page, if you go down to the overview)

Is that possible?

Winform desktop app and touch

I`ve a legacy winform desktop app that works perfectly with mouse and keyboard. It has some selfmade controls that involve the creation of threads and so on, for example, the longer a button is pushed the faster a number is incremented. The application also uses a win32 dll. Now, the client wants that aplication to be touch enabled and run it in a tablet, which also means resizing and rotation capabilyties.

My question is, which is the better way to get that aplication touch enabled and responsive design?

I can try to modify the existing winform, but I think it will be lot of work with poor result. I can also migrate to wpf and reuse the c# code, but I might have trouble with the keyboard, as I have not found a good way to show the keyboard and mantain the whole app on the screen. Or I can migrate to windows store app, but with the problem of that win32 dll, that I`m not sure it could be migrated.

The winform application is multilanguaje so creating a keyboard is not a valid option.

Any advice is welcome.

Thanks

WPF ComboBox Binding Errors

I've searched for hours and could not find any existing solutions to the problem I'm having. So here it is please help if you can. When I bind the combobox SelectedValuePath I am seeing BindingExpression path errors in the output window:

System.Windows.Data Information: 41 : BindingExpression path error: 'GeoUnitID' property not found for 'object' because data item is null. This could happen because the data provider has not produced any data yet. BindingExpression:Path=GeoUnitID; DataItem=null; target element is 'ComboBox' (Name=''); target property is 'NoTarget' (type 'Object')

System.Windows.Data Information: 20 : BindingExpression cannot retrieve value due to missing information. BindingExpression:Path=GeoUnitID; DataItem=null; target element is 'ComboBox' (Name=''); target property is 'NoTarget' (type 'Object')

System.Windows.Data Information: 21 : BindingExpression cannot retrieve value from null data item. This could happen when binding is detached or when binding to a Nullable type that has no value. BindingExpression:Path=GeoUnitID; DataItem=null; target element is 'ComboBox' (Name=''); target property is 'NoTarget' (type 'Object')

System.Windows.Data Information: 10 : Cannot retrieve value using the binding and no valid fallback value exists; using default instead. BindingExpression:Path=GeoUnitID; DataItem=null; target element is 'ComboBox' (Name=''); target property is 'NoTarget' (type 'Object')

The binding does work correctly, and the correct values are displayed, but I suspect these errors are the reason for the poor performance I am seeing (scrolling/loading timing). Here's the relevant xaml:

   <ListView x:Name="lvItems" Grid.Row="1" Grid.Column="0"
       ItemsSource="{Binding ElementName=myWindow, Path=Items, Mode=TwoWay}"
       gisc:ListViewSort.IsSortable="True">
        <ListView.View>
            <GridView>
                <GridView.Columns> 
                <!-- selecteditembinding: source:Int32, dest:dest:Int16  -->
                    <GridViewColumn>
                        <GridViewColumnHeader Tag="CountryOfIssue" Content="CountryOfIssue" />
                        <GridViewColumn.CellTemplate>
                            <DataTemplate>
                                <Grid>
                                    <ComboBox 
                                    ItemsSource="{Binding ElementName=myWindow, Path=Countries}" 
                                    SelectedValuePath="GeoUnitID"                                            
                                    SelectedValue="{Binding Path=CountryOfIssueID, Mode=TwoWay}"
                                    DisplayMemberPath="ShortName" 
                                    Style="{StaticResource GridEditStyle}" />
                                </Grid>
                            </DataTemplate>
                        </GridViewColumn.CellTemplate>
                    </GridViewColumn>
        </GridView.Columns>
    </GridView>
    </ListView.View>
    </ListView>

I've verified the ItemsSource collection does not have null items. I've also tried an entirely different structure (WPF datagrid instead of the Listview/Gridview structure shown above with similar results). The scrolling performance is terrible for a small number of rows (~400). I initially searched for ways to improve scrolling performance, but those solutions did little to help. There are TONS of these binding errors so I strongly suspect that is the root cause. Thanks for any help!

Value cannot be null error in System.Security.SecurityElement FromString

I have a WPF application and some of my customers are reporting this issue that occurs at launch. It doesn't occurs very often and I am unable to reproduce it. The data I have from some customers is showing that it happens on various type of computer (64 and 32 bits, intel, amd, pentium, Windows 7 or 8, etc.), I haven't found any correlation between the systems yet.

The only details I have at this time are these ones :

EXCEPTION MESSAGE : Value cannot be null. Parameter name: xml

TARGET SITE : System.Security.SecurityElement FromString(System.String)

INNER EXCEPTION :

SOURCE : mscorlib

STACKTRACE : at System.Security.SecurityElement.FromString(String xml) at System.Security.BuiltInPermissionSets.GetOrDeserializePermissionSet(NamedPermissionSet& permissionSet, String permissionSetXml) at System.Security.Policy.PolicyLevel.GetBuiltInSet(String name) at System.Security.Permissions.PermissionSetAttribute.CreatePermissionSet() at System.Security.PermissionSet.CreateSerialized(Object[] attrs, Boolean serialize, Byte[]& nonCasBlob, PermissionSet& casPset, HostProtectionResource fullTrustOnlyResources, Boolean allowEmptyPermissionSets) at DevExpress.Xpf.Docking.DockLayoutManager.UnsubscribeSystemEvents() at DevExpress.Xpf.Docking.DockLayoutManager.OnLoaded() at DevExpress.Xpf.Docking.VisualElements.psvControl.psvControl_Loaded(Object sender, RoutedEventArgs e) at System.Windows.RoutedEventHandlerInfo.InvokeHandler(Object target, RoutedEventArgs routedEventArgs) at System.Windows.EventRoute.InvokeHandlersImpl(Object source, RoutedEventArgs args, Boolean reRaised) at System.Windows.UIElement.RaiseEventImpl(DependencyObject sender, RoutedEventArgs args) at System.Windows.UIElement.RaiseEvent(RoutedEventArgs e) at System.Windows.BroadcastEventHelper.BroadcastEvent(DependencyObject root, RoutedEvent routedEvent) at System.Windows.BroadcastEventHelper.BroadcastLoadedEvent(Object root) at MS.Internal.LoadedOrUnloadedOperation.DoWork() at System.Windows.Media.MediaContext.FireLoadedPendingCallbacks() at System.Windows.Media.MediaContext.FireInvokeOnRenderCallbacks() at System.Windows.Media.MediaContext.RenderMessageHandlerCore(Object resizedCompositionTarget) at System.Windows.Media.MediaContext.RenderMessageHandler(Object resizedCompositionTarget) at System.Windows.Media.MediaContext.Resize(ICompositionTarget resizedCompositionTarget) at System.Windows.Interop.HwndTarget.OnResize() at System.Windows.Interop.HwndTarget.HandleMessage(WindowMessage msg, IntPtr wparam, IntPtr lparam) at System.Windows.Interop.HwndSource.HwndTargetFilterMessage(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean& handled) at MS.Win32.HwndWrapper.WndProc(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean& handled) at MS.Win32.HwndSubclass.DispatcherCallbackOperation(Object o) at System.Windows.Threading.ExceptionWrapper.InternalRealCall(Delegate callback, Object args, Int32 numArgs) at MS.Internal.Threading.ExceptionFilterHelper.TryCatchWhen(Object source, Delegate method, Object args, Int32 numArgs, Delegate catchHandler)

I really dont know where to dig so if someone have an idea where I should begin, that would be much appreciated.

Thanks

Binding to an array of structs in WPF

In my application I store an array of structs containing how much bills/coins i need to pay to a client and how many I effectively pay.

public struct MoneyType
{ //contains more, but left out for readability
   public int Requested { get; set; }  // How many are requested for a payment
   public int Paid { get; set; } //bills paid to the customer
}

I made an array with these which I make accessible to the viewmodel in the following way:

MoneyType[] money;  //correctly initialised in the constructor
public MoneyType[] GetMoney()
{
    return money;
}

In the viewmodel itself i make these accessible in this way:

public MoneyType[] MoneyTypes //Denominations
{
    get
    {
        return _dataService.GetMoney();
    }
} 

Finally, in my XAML, I accessed these as:

<cbtn:BillCounter x:Name="euro200" Value = "{Binding MoneyTypes[2].Paid, Mode=TwoWay }" />

The [2] is used to indicate which type of bills/coins i want to use.

However, now i want to make this work 2 ways, so that my custom control can update the amount of coins/bills paid. For which I would need a setter for my MoneyTypes property. However, i'm not sure i'm going the right way for this. I have a feeling that someway i should not pass the entire array from my viewmodel/model, but a specific part of one of my MoneyTypes (the paid/requested fields, with some kind of index indicating which entry to use), but i'm unsure of how to do this. Any tips on this?

Thanks!!

C# form display image and text on datagrid from sql

I Have a form with a database with images and text associated to each image Im trying to display all the data in the database on a form. I have a form with a picture box but when I call the stored data(using a button "View all" I only see one picture on my form. I thought perhaps a better way would be use a datagrid generated at run time to display "EID" "First Name" and "Last Name" as well as "Image" (the data stored in the database to allow for a proper display but am struggling to do so. How would I do it via datagridview to ensure that all my data are correctly displayed when the button "view all" is pressed. Apologies if some of this is unclear I am quite new to C#.Basically Im trying to display all database parameters for all entries on a datagrid

        try
        {
            string sql = "SELECT* FROM Employee";
            if (conn.State != ConnectionState.Open)
                conn.Open();
            SqlDataReader myReader = null;
            SqlCommand myCommand = new SqlCommand(sql,conn);
            myReader = myCommand.ExecuteReader();
            while (myReader.Read())
            {
                Console.WriteLine(myReader["EID"].ToString());
                Console.WriteLine(myReader["FIRST_NAME"].ToString());
                Console.WriteLine(myReader["LAST_NAME"].ToString());
                byte[] img = (byte[])(myReader["IMAGE"]);
                if (img == null)
                    pictureBox1.Image = null;
                else
                {
                    MemoryStream ms = new MemoryStream(img);
                    pictureBox1.Image = Image.FromStream(ms);
                }

            }


        }
        catch (Exception ex)
        {
            conn.Close();
            MessageBox.Show(ex.Message);
        }

WPF moving border around on screen

I'm making a game inventory system where I have a grid and borders that take up a grid space have a background image of the icon. For example in grid position 0,0 I have a border with a background of a health potion. I want to be able to drag this border to any other grid location. Right now I'm working on just clicking and dragging the border to follow the mouse.

What I have so far sort of works but not really. If sort of freaks out when I left click on the icon and move slowly. However I can move out of the icon fast and it doesn't keep up so it then stops moving until I'm back over it. Any ideas on how to get this kind of functionality?

public partial class MainWindow : Window
    {
        TranslateTransform trans = new TranslateTransform();
        Border border;

        public MainWindow()
        {
            InitializeComponent();

            // create a broder and set it's background image
            border = new Border();

            border.Visibility = System.Windows.Visibility.Visible;
            var img = (Image)MasterGrid.FindResource("notepad");
            var imgBrush = new ImageBrush(img.Source);
            border.Background = imgBrush;
            border.Margin = new Thickness(2.0);

            // add the border to the grid
            Grid.SetRow(border, 0);
            Grid.SetColumn(border, 1);
            Grid.SetRowSpan(border, 2);
            Grid.SetColumnSpan(border, 1);
            InvGrid.Children.Add(border);

            // hook up events
            _00.MouseUp += new System.Windows.Input.MouseButtonEventHandler(_00_MouseUp);
            border.MouseDown += border_MouseDown;
            border.MouseMove += border_MouseMove;
        }

        void border_MouseMove(object sender, MouseEventArgs e)
        {
            // make the border follow the mouse position
            trans.X = e.GetPosition(border).X;
            trans.Y = e.GetPosition(border).Y;
        }

        void border_MouseDown(object sender, MouseButtonEventArgs e)
        {
            border.RenderTransform = trans;
        }

        private void _00_MouseUp(object sender, System.Windows.Input.MouseButtonEventArgs e)
        {
            MessageBox.Show("test");
        }
    }

Select ListView Item by checking checkbox C#/WPF

I have UserControl with ListView, the ListView have TileView and the items contain Checkbox, Icon and label.

I found a way to check the checkbox with clicking on the Icon, but I want to select the item by checking the checkbox.

WPF adds black bar to Window

I have built a WPF application with a variable width and height (xaml height and width definition for the window is set to Auto). Once the contents of the window are loaded, the width does not (well, is not supposed to) change. The height might change as items are removed or added from the list.

The background is a gradient, not an image.

After a period where the application is idling and isn't the top-most, when switching back to the application, the window is wider as a black bar was added, extending the window to the right.
I've blurred out the content as it is unimportant here.
(Before this black bar appears, the window's width is the section with the blue gradient background)

I've added a hidden menu item to the window and when the user presses Alt the menu appears. At first, I simply added the menu and opening it caused the window to re-render as menu the item suddenly became visible and added to the window's height. As the window was re-rendered, the black bar disappeared and the window was its original width.

I tried the following solutions by adding an event where Window.OnFocus calls a function which:

  1. changes the width (adds 1 pixel and then removes 1 pixel)... but this doesn't seem to do anything.
  2. checks the width of the window. If the width is larger than the expected width, a re-render is manually called. But no dice...

What is causing this black bar to appear? How can I prevent it from happening?

The biggest problem here is that I can't seem to consistently reproduce the problem... sometimes, the application will sit open, idling in the background for the whole day and this won't happen. Sometimes, I'll go out to lunch, come back and there it is...

The content is loaded dynamically upon starting up, and there's a webservice call initiated every few minutes to check for changes. At this stage of development and testing, there aren't all that many changes happening so that the ui items are simply static most of the time. Even so, this black bar will appear at times after the application idles for a while, as mentioned.


Per suggestion, here is the xaml for the application:

MainWindow:

<Window x:Class="MyApp.MainWindow"
        xmlns="http://ift.tt/o66D3f"
        xmlns:x="http://ift.tt/mPTqtT"
        xmlns:y="clr-namespace:MyApp"
        Title="MyApp"
        Height="Auto" Width="390"
        SizeToContent="WidthAndHeight"
        WindowStyle="SingleBorderWindow"
        WindowStartupLocation="Manual"
        ResizeMode="CanMinimize">
    <Window.Resources>
        <BooleanToVisibilityConverter x:Key="BooleanToVisibilityConverter"/>
    </Window.Resources>
    <Grid Name="MainGrid" Style="{StaticResource Normal}">
        <Grid.RowDefinitions>
            <RowDefinition Height="18" />
            <RowDefinition Height="65"/>
            <RowDefinition Height="Auto" MinHeight="200"/>
        </Grid.RowDefinitions>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="150" />
            <ColumnDefinition Width="218" />
        </Grid.ColumnDefinitions>
        <Menu Grid.ColumnSpan="2"
              Visibility="{Binding Path=IsMenuVisible,
                                   RelativeSource={RelativeSource AncestorType=Window},
                                   Converter={StaticResource BooleanToVisibilityConverter}}">
            <MenuItem Header="File">
                <!--redacted other menu items-->
            </MenuItem>
        </Menu>
        <Image Grid.Row="1" Grid.Column="0" Source="http://packApplication:,,,/Resources/logo.png" Height="55" Width="118" HorizontalAlignment="Left" Margin="10,10,0,0" />
        <Grid Grid.Row="2" Grid.Column="0" Grid.ColumnSpan="2" Height="Auto" Width="Auto" x:Name="ContentGrid"></Grid>
    </Grid>
</Window>

MainPanel (which goes into the ContentGrid):

<UserControl x:Class="MyApp.MainPanel"
             xmlns="http://ift.tt/o66D3f"
             xmlns:x="http://ift.tt/mPTqtT"
             xmlns:mc="http://ift.tt/pzd6Lm" 
             xmlns:d="http://ift.tt/pHvyf2" 
             Height="Auto" Width="Auto" FlowDirection="RightToLeft">
    <Grid Margin="19,0,19,0">
        <Grid.RowDefinitions>
            <RowDefinition Height="65" />
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="75" />
        </Grid.RowDefinitions>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="160" />
            <ColumnDefinition Width="85" />
            <ColumnDefinition Width="85" />
        </Grid.ColumnDefinitions>
        <TextBlock Name="FirstHeader" Grid.Column="0" Grid.Row="0" Style="{StaticResource Header}" Text="***" />
        <TextBlock Name="SecondHeader" Grid.Column="1" Grid.Row="0" Style="{StaticResource Header}">***<LineBreak />***</TextBlock>
        <TextBlock Name="ThirdHeader" Grid.Column="2" Grid.Row="0" Style="{StaticResource Header}" Text="***" />
        <StackPanel Name="MainStack" Grid.Row="1" Grid.ColumnSpan="3" />
        <Button Name="ActionButton" Grid.ColumnSpan="3" Grid.Row="2" FlowDirection="LeftToRight" Style="{StaticResource NotInService}"  Click="ActionButton_Click" />
    </Grid>
</UserControl>

And the MainStack in the MainPanel is filled with these:

<UserControl x:Class="MyApp.mItem"
             xmlns="http://ift.tt/o66D3f"
             xmlns:x="http://ift.tt/mPTqtT"
             xmlns:mc="http://ift.tt/pzd6Lm" 
             xmlns:d="http://ift.tt/pHvyf2" 
             mc:Ignorable="d" 
             d:DesignHeight="35" d:DesignWidth="348" FlowDirection="RightToLeft">
    <Grid Margin="0,0,0,05">
        <Grid.RowDefinitions>
            <RowDefinition />
        </Grid.RowDefinitions>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="160" />
            <ColumnDefinition Width="85" />
            <ColumnDefinition Width="85" />
        </Grid.ColumnDefinitions>
        <Button Grid.Row="0" Grid.Column="0" Name="PanelActionButton" Style="{StaticResource PanelActionButton}" Click="PanelActionButton_Click">
            <TextBlock Name="AnswerButtonText" Style="{StaticResource ButtonText}"></TextBlock>
        </Button>
        <Label Grid.Row="0" Grid.Column="1" Name="SecondCol" Style="{StaticResource SecondCol}" />
        <Label Grid.Row="0" Grid.Column="2" Name="ThirdCol" Style="{StaticResource ThirdCol}" />
    </Grid>
</UserControl>

Oh, and the App file (styles):

<Application x:Class="MyApp.App"
             xmlns="http://ift.tt/o66D3f"
             xmlns:x="http://ift.tt/mPTqtT"
             StartupUri="MainWindow.xaml">
    <Application.Resources>
        <Style TargetType="{x:Type Control}" x:Key="CFontStyle">
            <Setter Property="FontFamily" Value="fonts/#Typograph" />
            <Setter Property="FontSize" Value="16" />
            <Setter Property="HorizontalAlignment" Value="Center" />
            <Setter Property="VerticalAlignment" Value="Center" />
        </Style>
        <Style TargetType="{x:Type TextBlock}" x:Key="TBFontStyle">
            <Setter Property="TextBlock.FontFamily" Value="fonts/#Typograph" />
            <Setter Property="FontSize" Value="16" />
            <Setter Property="Foreground" Value="White" />
            <Setter Property="VerticalAlignment" Value="Center" />
        </Style>
        <Style TargetType="{x:Type Label}" x:Key="LFontStyle">
            <Setter Property="Label.FontFamily" Value="fonts/#Typograph" />
            <Setter Property="FontSize" Value="20" />
            <Setter Property="FontWeight" Value="Bold" />
            <Setter Property="Height" Value="30" />
            <Setter Property="Foreground" Value="White" />
            <Setter Property="HorizontalAlignment" Value="Center" />
            <Setter Property="HorizontalContentAlignment" Value="Center" />
            <Setter Property="VerticalAlignment" Value="Center" />
        </Style>
        <Style TargetType="{x:Type Paragraph}" x:Key="PFontStyle">
            <Setter Property="FontSize" Value="12" />
        </Style>
        <Style TargetType="{x:Type Grid}" x:Key="Normal">
            <Setter Property="Background">
                <Setter.Value>
                    <RadialGradientBrush GradientOrigin="0.5,0.5" Center="0.5,0.5" RadiusX="1" RadiusY="1">
                        <RadialGradientBrush.GradientStops>
                            <GradientStop Color="#00AEEF" Offset="0" />
                            <GradientStop Color="#034ea2" Offset="1" />
                        </RadialGradientBrush.GradientStops>
                    </RadialGradientBrush>
                </Setter.Value>
            </Setter>
            <Setter Property="FlowDirection" Value="RightToLeft" />
        </Style>
        <Style BasedOn="{StaticResource CFontStyle}" TargetType="{x:Type Button}" x:Key="NotInService">
            <Setter Property="Width" Value="104" />
            <Setter Property="Height" Value="37" />
            <Setter Property="Template">
                <Setter.Value>
                    <ControlTemplate TargetType="{x:Type Button}">
                        <Grid>
                            <Border>
                                <Border.Background>
                                    <ImageBrush ImageSource="http://packApplication:,,,/Resources/service_button_OUT.png" Stretch="Fill" TileMode="None" />
                                </Border.Background>
                            </Border>
                            <ContentPresenter Content="{TemplateBinding Content}"/>
                        </Grid>
                        <ControlTemplate.Triggers>
                            <Trigger Property="IsMouseOver" Value="True">
                                <Setter Property="Cursor" Value="Hand" />
                            </Trigger>
                        </ControlTemplate.Triggers>
                    </ControlTemplate>
                </Setter.Value>
            </Setter>
        </Style>
        <Style BasedOn="{StaticResource CFontStyle}" TargetType="{x:Type Button}" x:Key="InService">
            <Setter Property="Width" Value="104" />
            <Setter Property="Height" Value="37" />
            <Setter Property="Template">
                <Setter.Value>
                    <ControlTemplate TargetType="{x:Type Button}">
                        <Grid>
                            <Border>
                                <Border.Background>
                                    <ImageBrush ImageSource="http://packApplication:,,,/Resources/service_button_IN.png" Stretch="Fill" TileMode="None" />
                                </Border.Background>
                            </Border>
                            <ContentPresenter Content="{TemplateBinding Content}"/>
                        </Grid>
                        <ControlTemplate.Triggers>
                            <Trigger Property="IsMouseOver" Value="True">
                                <Setter Property="Cursor" Value="Hand" />
                            </Trigger>
                        </ControlTemplate.Triggers>
                    </ControlTemplate>
                </Setter.Value>
            </Setter>
        </Style>
        <Style BasedOn="{StaticResource CFontStyle}" TargetType="{x:Type Button}" x:Key="WaitForService">
            <Setter Property="Width" Value="104" />
            <Setter Property="Height" Value="37" />
            <Setter Property="Template">
                <Setter.Value>
                    <ControlTemplate TargetType="{x:Type Button}">
                        <Grid>
                            <Border>
                                <Border.Background>
                                    <ImageBrush ImageSource="http://packApplication:,,,/Resources/service_button_WAIT.png" Stretch="Fill" TileMode="None" />
                                </Border.Background>
                            </Border>
                            <ContentPresenter Content="{TemplateBinding Content}"/>
                        </Grid>
                        <ControlTemplate.Triggers>
                            <Trigger Property="IsMouseOver" Value="True">
                                <Setter Property="Cursor" Value="No" />
                            </Trigger>
                        </ControlTemplate.Triggers>
                    </ControlTemplate>
                </Setter.Value>
            </Setter>
        </Style>
        <Style BasedOn="{StaticResource CFontStyle}" TargetType="{x:Type Button}" x:Key="PanelActionButton">
            <Setter Property="Width" Value="160" />
            <Setter Property="Height" Value="40" />
            <Setter Property="Foreground" Value="#414042" />
            <Setter Property="Template">
                <Setter.Value>
                    <ControlTemplate TargetType="{x:Type Button}">
                        <Grid>
                            <Border>
                                <Border.Background>
                                    <ImageBrush ImageSource="http://packApplication:,,,/Resources/pancel_action_button.png" Stretch="Fill" TileMode="None" />
                                </Border.Background>
                            </Border>
                            <ContentPresenter Content="{TemplateBinding Content}"/>
                        </Grid>
                        <ControlTemplate.Triggers>
                            <Trigger Property="IsMouseOver" Value="True">
                                <Setter Property="Cursor" Value="Hand" />
                            </Trigger>
                        </ControlTemplate.Triggers>
                    </ControlTemplate>
                </Setter.Value>
            </Setter>
        </Style>
        <Style TargetType="{x:Type TextBlock}" x:Key="ButtonText">
            <Setter Property="TextAlignment" Value="Left" />
            <Setter Property="FlowDirection" Value="RightToLeft" />
            <Setter Property="Margin" Value="15,0,15,0" />
            <Setter Property="VerticalAlignment" Value="Center" />
        </Style>
        <Style BasedOn="{StaticResource LFontStyle}" TargetType="{x:Type Label}" x:Key="SecondCol">
            <Setter Property="Effect">
                <Setter.Value>
                    <DropShadowEffect BlurRadius="5" ShadowDepth="0" Opacity="1" Direction="315" Color="Black"/>
                </Setter.Value>
            </Setter>
        </Style>
        <Style BasedOn="{StaticResource LFontStyle}" TargetType="{x:Type Label}" x:Key="ThirdCol">
            <Setter Property="Effect">
                <Setter.Value>
                    <DropShadowEffect BlurRadius="5" ShadowDepth="0" Opacity="1" Color="Black"/>
                </Setter.Value>
            </Setter>
        </Style>
        <Style BasedOn="{StaticResource TBFontStyle}" TargetType="{x:Type TextBlock}" x:Key="Header">
            <Setter Property="HorizontalAlignment" Value="Center" />
            <Setter Property="TextAlignment" Value="Center" />
            <Setter Property="TextWrapping" Value="Wrap" />
            <Setter Property="Effect">
                <Setter.Value>
                    <DropShadowEffect BlurRadius="3" ShadowDepth="0" Opacity="1" Color="Black"/>
                </Setter.Value>
            </Setter>
        </Style>
    </Application.Resources>
</Application>

How to draw polygons on canvas using mouse events?

I'm approaching WPF drawing world (using .NET 4.5 and VS2013) and I'm struggling with the following question: I'd like to draw a polygon on a canvas using mouse click/move events. On the web I saw some static examples(i.e. points carved in XAML/C# code), using WebForms or GDI but that doesn't suites my needs. It would be great if someone could provide a simple example, no need for the fancy stuff (like moving or resizig the polygon).

EDIT: My requirements are exactly the same as the one of the following OP:

Drawing Line to next point in realtime

The answer marked as best is near but not exactly what I need. I tried this:

    <Canvas  Name="canvas" 
             MouseMove="Canvas_MouseMove" 
             MouseLeftButtonDown="Canvas_MouseLeftButtonDown"  
             MouseLeftButtonUp="Canvas_MouseLeftButtonUp"
             MouseRightButtonDown="Canvas_MouseRightButtonDown">
        <Canvas.Background>
            <SolidColorBrush Color="White" Opacity="0"/>
        </Canvas.Background>
    </Canvas>

C#:

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
    }
    private Polygon p;
    private Polyline segment = new Polyline();

    private void Canvas_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
    {
        if (p == null)
        {
            var canvas = (Canvas)sender;
            var point = e.GetPosition(canvas);

            // create new polyline
            p = new Polygon();
            p.Stroke = Brushes.Black;
            p.Points.Add(point);
            canvas.Children.Add(p);

            // initialize current polyline segment
            segment.Stroke = Brushes.Red;
            segment.Points.Add(point);
            segment.Points.Add(point);
            canvas.Children.Add(segment);
        }
    }

    private void Canvas_MouseMove(object sender, MouseEventArgs e)
    {
        if (p != null)
        {
            // update current polyline segment
            var canvas = (Canvas)sender;
            segment.Points[1] = e.GetPosition(canvas);
            segment.Stroke = Brushes.Blue;
        }
    }

    private void Canvas_MouseRightButtonDown(object sender, MouseButtonEventArgs e)
    {
        p = null;
        segment.Points.Clear();
        canvas.Children.Remove(segment);
    }
    private void Canvas_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
    {
        if (p != null)
        {
            var canvas = (Canvas)sender;
            segment.Points[1] = e.GetPosition(canvas);

            p.Points.Add(segment.Points[1]);
            segment.Points[0] = segment.Points[1];
        }
    }
}

  1. The code above draws a polygon after each mouse click, I would like to draw it only at the end of the process (let's say after a right click).
  2. It starts drawing the first line while dragging the mouse, it would be nicer to have "click once to anchor the first point, click on another spot to anchor the second one, draw a line between them etc.".

SQLite DB access using clickonce generated shortcut

I'm using a SQLite DB in my program, and it runs without issue in VS or looking in my debug folder. I then deploy a clickonce application and after installing it fails to access the database, the exact error I'm getting is:

SQLite Error

Now if I go into where the clickonce application is installed and run the program from that folder it runs without issue, I only get the problem when using the shortcut generated by the clickonce application.

Anyone have any thoughts on why? Thanks in advance for any insight.

How to modify WPF forms so that they work with different scaling levels on Windows?

Say that I have a simple WPF form with some text in it.

When I show the form on a display that has normal scaling (scaling set to 100% in Control Panel\Appearance and Personalization\Display) it looks great.

When I show the form on a display with higher scaling (for example 200%) the text and controls no longer fit.

Is there a simple way to make the form work on all scaling levels?

Checkbox column flickering when scrolling

I want to make a simple table, whit a checkbox column. I created the table as DataGrid and bound it to a List of custom objects.

Everything works fine, except I notice strange flickering effect, when I scroll the table.
It looks like this: http://ift.tt/1J5ufg3

What's the problem? How can I get rid of this?

My xaml code:

<Window x:Class="MainWindow"
xmlns="http://ift.tt/o66D3f"
xmlns:x="http://ift.tt/mPTqtT"
Title="MainWindow" Height="350" Width="723.251">

<Grid>
    <DataGrid x:Name="MainDataGrid" Margin="22,21,133,58" 
              AutoGenerateColumns="False"
              SelectionMode="Single"
              SelectionUnit="Cell"
              CanUserSortColumns="False"
              IsReadOnly="True"
              >
    </DataGrid>
    <Button Content="Populate" HorizontalAlignment="Left" Margin="592,21,0,0" VerticalAlignment="Top" Width="75" Click="Button_Click" IsDefault="True"/>
    <Label x:Name="Lbl1" Content="Label" HorizontalAlignment="Left" Margin="592,48,0,0" VerticalAlignment="Top"/>
</Grid>
</Window>

And vb code:

Imports CADnet_FileReader.CADnet_FileReader

Class MainWindow

Dim OutList As New List(Of Tags)
Dim SelectionLock As New Boolean

Private Sub Button_Click(sender As Object, e As RoutedEventArgs)
    Dim TableColumn_01 As New DataGridTextColumn
    TableColumn_01.Binding = New Binding("TagItem")
    TableColumn_01.Header = "Tag Name"
    TableColumn_01.Width = 200
    Me.MainDataGrid.Columns.Add(TableColumn_01)

    Dim TableColumn_02 As New DataGridCheckBoxColumn

    TableColumn_02.Binding = New Binding("TagCheck")
    TableColumn_02.Header = "Toogle"
    TableColumn_02.Width = 30

    Me.MainDataGrid.Columns.Add(TableColumn_02)

    Dim TempList As New List(Of String)
    Dim path As String = "C:\Epic\Apps\ElementCounter\Epic_Template.txt"
    TempList = ReadTemplateFile(path)

    Dim ThisItem As New Tags

    For i = 0 To TempList.Count - 1
        ThisItem = New Tags
        ThisItem.TagItem = TempList.Item(i)
        ThisItem.TagCheck = False
        OutList.Add(ThisItem)
    Next

    MainDataGrid.ItemsSource = OutList
End Sub

Private Sub MainDataGrid_SelectionChanged(sender As Object, e As SelectionChangedEventArgs) Handles MainDataGrid.SelectionChanged
End Sub

Private Sub MainDataGrid_SelectedCellsChanged(sender As Object, e As SelectedCellsChangedEventArgs) Handles MainDataGrid.SelectedCellsChanged
    Dim SelectedRow As Integer
    Dim SelectedColumn As Integer

    SelectedRow = MainDataGrid.Items.IndexOf(MainDataGrid.CurrentItem)
    SelectedColumn = MainDataGrid.SelectedCells.Item(0).Column.DisplayIndex

    Lbl1.Content = "Selected Row = " & SelectedRow & "; " & SelectedColumn

    If SelectedColumn = 1 Then
        If OutList.Item(SelectedRow).TagCheck = False Then
            OutList.Item(SelectedRow).TagCheck = True
        Else
            OutList.Item(SelectedRow).TagCheck = False
        End If


    End If

End Sub
End Class

List item I used:

<System.Serializable()> Public Class Tags
    Implements INotifyPropertyChanged
    Public Property TagItem As String
    ' New Property
    Private _NewDataProperty As String
    Public Property TagCheck
        Set(value)
            _NewDataProperty = value
            _PropertyChanged("TagCheck")
        End Set
        Get
            Return _NewDataProperty
        End Get
    End Property
    ' Change events
    Private Sub _PropertyChanged(Optional ByVal PropertyName As String = Nothing)
        RaiseEvent PropertyChanged(Me, New PropertyChangedEventArgs(PropertyName))
    End Sub
    Private Event PropertyChanged(sender As Object, e As PropertyChangedEventArgs) Implements INotifyPropertyChanged.PropertyChanged

    Public Sub SerializeMe()
    End Sub
End Class

WPF - Toggle Button - Beveled Effect

I've been trying to create a toggle button with a "simple" bevel effect for my WPF Window. At first I've tried to apply the BevelBitmapEffect but apparently it is not deprecated and there are no visual changes when applied. I've have tried many other "tweaks" with no success.

The kind of button I'm going for is something like this: Beveled Button

Edit: I was able to create this effect by having two pictures (unpressed and pressed). Still, if anyone knows how to do this without any external resources that would be great.

Thank you!

Add row without changing all Column/Row id

I've a huge grid in wpf (xaml)

<Grid Width="400" Height="400">
<Grid.RowDefinitions>
    <RowDefinition Height="Auto"></RowDefinition>
    <RowDefinition Height="Auto"></RowDefinition>
    <RowDefinition Height="Auto"></RowDefinition>
    <RowDefinition Height="Auto"></RowDefinition>
    <RowDefinition Height="Auto"></RowDefinition>
    <RowDefinition Height="Auto"></RowDefinition>
    <RowDefinition Height="Auto"></RowDefinition>
    <RowDefinition Height="Auto"></RowDefinition>
    <RowDefinition Height="Auto"></RowDefinition>
    ...
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
    <ColumnDefinition></ColumnDefinition>
    <ColumnDefinition></ColumnDefinition>
</Grid.ColumnDefinitions>


<Label>1</Label>
<TextBox Grid.Column="1"></TextBox>

<Label Grid.Row="1">1</Label>
<TextBox Grid.Column="1" Grid.Row="1"></TextBox>

<Label Grid.Row="2">2</Label>
<TextBox Grid.Column="1" Grid.Row="2"></TextBox>

...
...
...

I would like to add a row at the top of my grid. For now, I change Grid.Row="1" by Grid.Row="2" and Grid.Row="2" by Grid.Row="3" ... It's really painful !

Is there any solution to add rows without changing all ID ?

Thanks

How to play Track when getting Id on Mixradio API

I'm getting id each items of track but I don't play it as next,back, play, pause...

E.g: I have items name is "Blank Space" song and is "015668". Now. How to play Blank Space song with id 015668.

I dont see tutorial about that and Have other media player API support wpf,universal app for mp3 and video stream youtube

Selected Value return False instead of the item

am triyng to you WPF binding it return False instead of my the item I selected

this is my Xaml: code:

ComboBox Name="cbKeyboardLayout" ItemsSource="{Binding AvailableKeyboardLayouts}" HorizontalAlignment="Right" Margin="0,2,20,2" SelectedItem="{Binding Path=SelectedKeyboardLayout, Mode=TwoWay, Converter={StaticResource kbConverter}, FallbackValue=English}" Width="120"

and this is the return

    /// <summary>
    /// Get/set the language setting for this keyboard.
    /// </summary>
    public string SelectedKeyboardLayout
    {
        get
        {
            //Debug.WriteLine("KeyboardViewModel.SelectedKeyboardLayout.get, returning " + _selectedKeyboardLayout);
            return _selectedKeyboardLayout;
        }
        set
        {
            //Debug.WriteLine("KeyboardViewModel.SelectedKeyboardLayout.set, from " + _selectedKeyboardLayout.ToString() + " to " + value.ToString());

            _selectedKeyboardLayout = value;

                if (_selectedKeyboardLayout != "Unknown")
                {
                    SetKeyAssignmentsTo(_selectedKeyboardLayout);
                    VirtualKeyboardRegistryService.TheVirtualKeyboard.TheKeyboardLayout = value;
                    Notify("SelectedKeyboardLayout");
                }

            SetFocusOnTarget();
        }
    }

Helix 3d toolkit: How to draw a rounded cube?

How would I go about drawing a rounded cube, like a dice?

I have tried using CubeVisual3D but only seems to give 90 degree edges.

WPF: is there a way to do inline formatting?

Is there a way to use inline formatting (like Swing's HTML tagging within labels) with WPF? I could not find any documentation.

How should i use VirtualScreenLeft and VirtualScreenTop

In my application i need to know size of all monitors combined space, to adjust size of the window if it goes to big.

I found VirtualScreenWidth and VirtualScreenHeight in System.Windows.SystemParameters and it seems like what i need. But also i wonder what is VirtualScreenLeft and VirtualScreenTop and how i should take it in consideration? In which scenarios this values are set to not 0?

Serial Port - reading data/updating canvas element

I've been having issues for a few weeks now reading in data from a serial port and updating a canvas element based on the message being received. The canvas element to be updated is a small image, that is supposed to rotate to a certain angle based on the third section of the message being received. I'm not sure what's going wrong, it seems that a full message isn't always being received. I'm going to give as much detail about the port and data. Structure - 8 data bits, 1 start bit, 1 stop bit, no parity. Message frequency is 15 Hz (the number of lines written every second). The default baud rate is 9,600.

There are five sections: 1. Section1 - two decimal places. 2. Section2 - two decimal places. 3. Angle - multiplied by 10 – i.e. 256.0 degrees is shown as 2560. 4. Section4 multiplied by -100 – i.e. 6.66 degrees is -666. 5. Section5 multiplied by 100 – i.e. 55.5 degrees is 555. A message starts with a colon symbol (:) and ends with . A field that contains asterisks, '***', indicates that no value is defined for that field.

An example to illustrate:

Column 
1 15 22 29 36 43 
1.00 *** 0 0 0 
: 1.00 20.20 2460 0 0
: 2.40 20.45 2460 10000 -10000 
: 3.00 20.45 2355 1000 554

I have the latest message received being shown at the top of the window to ensure the user that data is being received, but I noticed the message is only show bits and pieces of what it should be, and thus messing up the rotation of the canvas element. So for instance, the message might be : 20 500 at first, and then get a complete message.

Here's a screenshot of the data being sent: Data received

Here's relative code in my MainWindow.cs:

    private Port port = new Port();
    private double rovHeading;
    Point rotate_Origin = new Point(0.5, 0.5);
    public string LastCOMMessage
    {
        get { return (string)this.GetValue(LastCoMMessageProperty); }
        set { this.SetValue(LastCoMMessageProperty, value); }

    }
    private void Connect_Port(object sender, RoutedEventArgs e)
    {
        if (port.Status == Port.PortStatus.Disconnected)
        {
            try
            {
                port.Connect("COM1", 9600, false, 250); //When set to false, test data is used on Connect. Last parameter is how often the UI is updated. Closer to 0, the faster it updates.

                //Sets button State and Creates function call on data recieved
                Connect_btn.Content = "Disconnect";

                port.OnMessageReceived += new Port.MessageReceivedHandler(port_OnMessageReceived);
            }

            catch (Exception)
            {
                System.Windows.MessageBox.Show("Port is not available.");
            }
        }

        else
        {
            try // just in case serial port is not open, could also be achieved using if(serial.IsOpen)
            {
                port.Disconnect();
                Connect_btn.Content = "Connect";
            }

            catch
            {
            }
        }
    }

    /// <summary>
    /// Reads in the data streaming from the port, taking out the third value which is the ROV's heading and assigning it to rovHeading.
    /// It then calls orientRovImage.
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    private void port_OnMessageReceived(object sender, Port.MessageEventArgs e)
    {
        LastCOMMessage = e.Message;

        if (rovImage != null && e.Message.EndsWith("\r\n")) //messages end in <CR><LF>. Was having issues where only half a message would be received and updated the heading to wrong number.
        {
            string[] messageComponents = LastCOMMessage.Split(" ".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);

            if (messageComponents.Length >= 3)
            {
                double.TryParse(messageComponents[3], out rovHeading);

                if (rovHeading > 0)
                {
                    rovHeading /= 10;

                    orientRovImage();
                }
            }
        }
    }

    /// <summary>
    /// Rotates the ROV icon based on the heading being streamed in.
    /// </summary>
    private void orientRovImage()
    {
        RotateTransform rotateRov = new RotateTransform(rovHeading + angle_Offset);
        rovImage.RenderTransformOrigin = rotate_Origin;
        rovImage.RenderTransform = rotateRov;
    }

Here's my Port.cs:

class Port
{
    private SerialPort serial = null;
    private DispatcherTimer testTimer;
    private string[] testData = new string[] { ": 3.00 20.45 2355   1000 554\r\n", ": 5.00 78.09 1725 3200 121\r\n", ": 9.20 10.12 1492 8820 197\r\n" }; //test data to be sent when liveData is set to false.
    private int testDataIndex = -1;
    private DateTime dateOflastMessageHandled;

    public enum PortStatus
    {
        Connected,
        Disconnected
    }
    public PortStatus Status { get; private set; }
    public bool LiveData { get; private set; }
    public int MillisecondsDelayBetweenMessages { get; private set; }

    public class MessageEventArgs : EventArgs
    {
        public string Message { get; private set; }

        public MessageEventArgs(string message)
        {
            Message = message;
        }
    }
    public delegate void MessageReceivedHandler(object sender, MessageEventArgs e);
    public event MessageReceivedHandler OnMessageReceived;


    private void MessageReceived(string message)
    {
        if (OnMessageReceived == null)
        {
            return;
        }

        OnMessageReceived(this, new MessageEventArgs(message));
    }


    public Port()
    {
        Status = PortStatus.Disconnected;
    }

    public void Connect(string portName, int baudRate, bool liveData, int millisecondsDelayBetweenMessages)
    {
        LiveData = liveData;
        MillisecondsDelayBetweenMessages = millisecondsDelayBetweenMessages;

        Disconnect();

        if (liveData)
        {
            serial = new SerialPort();

            serial.PortName = portName;
            serial.BaudRate = baudRate;
            serial.Handshake = Handshake.None;
            serial.Parity = Parity.None;
            serial.DataBits = 8;
            serial.StopBits = StopBits.One;
            serial.ReadTimeout = 200;
            serial.WriteTimeout = 50;

            serial.Open();

            serial.DataReceived += new SerialDataReceivedEventHandler(Receive);
        }

        else
        {
            testTimer = new DispatcherTimer();
            testTimer.Interval = new TimeSpan(0, 0, 0, 0, 3);
            testTimer.Tick += new EventHandler(testTimer_Tick);
            testTimer.Start();
        }

        Status = PortStatus.Connected;
    }


    private void testTimer_Tick(object sender, EventArgs e)
    {
        if (dateOflastMessageHandled == null || DateTime.Now.Subtract(dateOflastMessageHandled).TotalMilliseconds >= MillisecondsDelayBetweenMessages)
        {
            dateOflastMessageHandled = DateTime.Now;
            MessageReceived(testData[testDataIndex]);

            testDataIndex++;
            if (testDataIndex >= testData.Length)
            {
                testDataIndex = 0;
            }
        }
    }


    private void Receive(object sender, SerialDataReceivedEventArgs e)
    {
        if (dateOflastMessageHandled == null || DateTime.Now.Subtract(dateOflastMessageHandled).TotalMilliseconds >= MillisecondsDelayBetweenMessages)
        {
            dateOflastMessageHandled = DateTime.Now;

            Application.Current.Dispatcher.BeginInvoke(new Action(
                delegate()
                {
                    //MessageReceived(serial.ReadLine());
                    MessageReceived(serial.ReadExisting());
                }));
        }
    }


    public void Disconnect()
    {
        if (testTimer != null)
        {
            testTimer.Stop();
        }

        testDataIndex = 0;

        Status = PortStatus.Disconnected;

        if (serial != null)
        {
            serial.Close();
        }
    }
}

And finally in my MainWindow.xaml, this just shows the last message received:

        <Button Content="Connect" Click="Connect_Port" Name="Connect_btn" />
        <TextBlock Text="{Binding LastCOMMessage, ElementName=this}" />

Any hints or help with this would be much appreciated, as this is the first time I've worked w/ ports. Thanks!

Creating a WPF divided diagram

So there's this tutorial about creating a diagram in WPF. http://ift.tt/1BoaBo0

I've read it, and still studying it to understand it completely.

At the end of this tutorial, you can basically add shapes, move/rotate/scale them, and since they are created in a vector form, they are keeping their resolutions, there are also connectors that can connect each shape with another.

My goal, since I need to create a simulator which shows how internet protocols are delivered, is to create a divided diagram in which Side A communicates with Side B. it could read an automata and simulate the transitions in the diagram.

I'm thinking of how to deliever this, and since I don't have a lot of knowledge in WPF, I wonder in which way should I implement it.

Should I create 2 different Canvases? or maybe dividing 1 canvas with two sides?

The main issue I'm dealing with, is that when a shape is being dragged to the end margin of the window, then the window allow me to slide it so I can see the rest of the field, this is being done by increasing the size of the Canvas, as seen in the Tutorial Part 1. However, if my canvas is divided by two, and there's a border in the middle, how can I create two sliders for each of the sides?

I was wondering if you can give me any tips about how approaching this idea, since my knowledge in WPF is still very limited.

WPF GridViewColumn align doesnt work

I want the information in GridViewColumn "from" aligned to the right.

This is what I have done and its not working:

    <ListView ItemsSource="{Binding VolumeNumber}" HorizontalAlignment="Stretch" HorizontalContentAlignment="Stretch" >
       <ListView.View>
          <GridView AllowsColumnReorder="False">
             <GridViewColumn Header="SomeStatus" DisplayMemberBinding="{Binding Name}" Width="170" />
             <GridViewColumn Header="from" DisplayMemberBinding="{Binding Value, StringFormat=0.000000}" Width="170 >
                <GridViewColumn.CellTemplate>
                   <DataTemplate>
                      <TextBlock TextAlignment="Right" Width="40"/>
                   </DataTemplate>
                </GridViewColumn.CellTemplate>
             </GridViewColumn>
          </GridView>
       </ListView.View>
    </ListView>

Clearing and refilling a bound combo box

I have a WPF application with a number of comboboxes that tie together. When I switch comboboxx #1, combobox #2 switches, etc.

Here is the xaml for the 2 comboboxes:

<ComboBox Grid.Row="1" Height="23" HorizontalAlignment="Right" Margin="0,12,286,0" ItemsSource="{Binding}" Name="CboDivision" VerticalAlignment="Top" Width="120" SelectionChanged="CboDivision_SelectionChanged" />
<ComboBox Height="23" HorizontalAlignment="Right" Margin="0,9,32,0" Name="CboCustomerList" ItemsSource="{Binding}" VerticalAlignment="Top" Width="120" SelectionChanged="CboCustomerList_SelectionChanged" Grid.Row="1" />

CboDivision gets populated at the beginning and doesnt need a reset. When I do an index change it calls a backgroundworker which calls the following code:

        private void CboCustomerList_DoWork(object sender, DoWorkEventArgs e)
        {
            if (RdoItemSearch.IsChecked == false) return;

            Mouse.OverrideCursor = System.Windows.Input.Cursors.Wait;
            string connectionString = Settings.Default.ProdConnectionString;
            SqlConnection connection = new SqlConnection(connectionString);

            SqlCommand SqlCmd = new SqlCommand();
            SqlCmd.CommandType = CommandType.StoredProcedure;
            SqlCmd.CommandText = "sp_GetItemIds";
            SqlCmd.Parameters.Add("@customer", SqlDbType.NVarChar).Value = CboCustomerList.SelectedValue.ToString().Trim();
            SqlCmd.Connection = connection;
            SqlDataReader reader = null;
            connection.Open();
            reader = SqlCmd.ExecuteReader();

            while (reader.Read())
            {
                CboItemId.Items.Add(reader["EXTITEM"].ToString());
            }
}

The problem is that i am unable to switch selections on CboDivision and have CboCustomerList clear and reload new values into it. Is it the way I'm binding the values in the xaml? How can I have a change in CboDivision cause a clearing of CboCustomerList items, then the execution of the filling routine?

i am currently resetting the combobox with:

CboCustomerList.SelectedIndex = -1;

but this just appends the new cbocustomerlist query to the end I also tried

CboCustomerList.Items.Clear()

but that just returns a null reference error after the box is refilled and the user selects an item.

Enable Parent window menus on child button login event in WPF MVVM

I have a scenario, I am having a MainWindow.xaml. This window has menus (which are initially disabled) and user controls. On one of the user control I have a login button clicking which Login pop up window open up. After successful login I want to Enable my main window disabled menu items. How can I achieve this functionality in WPF MVVM?

How to focus and expand a particular row in telerik RadTreeListView?

I wrote one simple program to test and show my list in telerik RadTreeListView, as shown below :

Definition a property :

List<Package> Packages { get; set; }

In Constructors :

public MainWindow()
    {
        InitializeComponent();
        Packages = CreatePachage();
        BindData();
    }

Definition of BinData() for craate resource :

private void BindData()
    {
        Packages = new List<Package>(Packages);
        TlvPackage.ItemsSource = Packages;
    }

Definition of CreatePachage() :

private List<Package> CreatePachage()
    {
        var p = new List<Package>
            {
                new Package
                {
                    PackageId = 1,
                    Name = "p1",
                    Version = "1.1.1.1",
                    Count = 15,
                    Items = new Collection<Package>
                    {
                        new Package {PackageId = 11,Name = "P.1.1", Version = "1.1", Count = 12},
                        new Package {PackageId = 12,Name = "P.1.1", Version = "1.1", Count = 12},
                        new Package {PackageId = 13,Name = "P.1.2", Version = "1.2", Count = 13}
                    }
                },
                new Package
                {
                    PackageId = 14,
                    Name = "p2",
                    Version = "2.2.2.2",
                    Count = 15,
                    Items = new Collection<Package>
                    {
                        new Package {PackageId = 18,Name = "P.2.2", Version = "2.2", Count = 13},
                        new Package {PackageId = 19,Name = "P.2.2", Version = "2.2", Count = 13}
                    }
                },
                new Package
                {
                    PackageId = 20,
                    Name = "p3",
                    Version = "3.3.3.3",
                    Count = 15,
                    Items = new Collection<Package>
                    {
                        new Package {PackageId = 48,Name = "P.3.2", Version = "3.2", Count = 13},
                        new Package {PackageId = 49,Name = "P.3.2", Version = "3.2", Count = 13}
                    }
                }
            };
        return p;
    }

Now, i want to update on row of resorce of bind to RadTreeListView, as shown below :

private void BtnEdit_OnClick(object sender, RoutedEventArgs e)
    {
        var currentItem = TlvPackage.SelectedItem as Package;
        var frm = new AddEdit { DataContext = currentItem };
        if (frm.ShowDialog() == true)
        {
            BindData();
        }
    }

But after the update list expanded all item and close nodes and not focus to current item of edited.How to do this work???

WPF How to reuse Popup window xaml fragment to show on multiple different button clicks

I have a created a Popup window in xaml which is opened on clicking a button. I need the same Popup on clicking some other button. Is there a clean way to reuse this popup without copy pasting it directly inplace?

Combine/Merge several inkcanvas strokes into one stroke?

I'm creating a simple inkcanvas app and I would like to implement a "combine strokes" function, but I can't find any information about how to merge two different strokes to be treated as only one. Is this possible?

Thanks in advance

WPF listview - rebound effect

I'm writing a WPF application, touch on. I would like to add to the ListView rebound effect (at the beginning and end of the list) such as Windows Phone or Windows 8. Does anyone have any idea on this?

How can I get the whole text content from a Paragraph(System.Windows.Documents)?

I think the question title is self explaining enough. I've added some strings via ParagraphControl.Inlines.Add(SomeStringValue) and I'm some getting troubles retrieving the text content. Any tip?

How to set DesiredSize greater than ConstraintSize using MeasureOverride method

I have a custom control, which load inner control set based on user configuration. Inner control set can contain two types of controls - some of them has custom attached boolean property, which says that inner control can take only desired space (false value by default) or control can take all remaining space (true value).

In outer control MeasureOverride method is overriden as well as in inner control. Outer control calls Measure method on all children which has default value of attached property with double.InfinitePositive value as constraint height. Children, where attached property equal to true are measured with (remaining space/number of children with attached property equal to true) as constraint size height.

Everything works as expected. Inner controls are properly measured, but here is problem if constraint height is smaller than inner control calculated height. in that case, after calling measure on inner control child.DesiredSize.Height is equal to constraint and child.ActualHeight is equal to child MeasureOverride output size height value.

How can I say to outer control that child's Desired size is output value from child.MeasureOverrride method?

Example of code goes here: MeasureOverride method of outer control:

protected override Size MeasureOverride(Size availableSize)
    {
        //size which can be used as constraint for children
        Size constraintSize = new Size(availableSize.Width, double.PositiveInfinity);

        //FixedElements has attached property value equal to false
        foreach (FrameworkElement child in FixedElements)
        {
            child.Measure(constraintSize);
        }
        double fixedElementDesiredHeights = FixedElements.Sum(element => element.DesiredSize.Height);

        //fixed element heights are higher than desired height
        if (fixedElementDesiredHeights > DesiredMaxHeight)
        {
            foreach (FrameworkElement stretchedElement in StretchedElements)
            {                    
                stretchedElement.Measure(constraintSize);
            }
        }
        else
        {
            //DesiredMaxHeight is expected height of outer value
            var difference = DesiredMaxHeight - fixedElementDesiredHeights;
            var visibleStretchedElements = StretchedElements.Count(element => element.IsVisible);

            var stretchedSize = new Size(availableSize.Width, visibleStretchedElements == ZERO ? difference : difference / visibleStretchedElements);
            foreach (FrameworkElement stretchedElement in StretchedElements)
            {
                stretchedElement.Measure(stretchedSize);
                //if stretchedSize is smaller than output value from stretchedElement MeasureOverride method, stretchedElement.DesiredSize is equal to stretchedSize. But I expect stretchedElement.DesiredSize to be the same as stretchedElement MeasureOverride output value.
            }                
        }

        double stretChableElementsDesiredHeights = StretchedElements.Sum(element => element.DesiredSize.Height);            
        double height = fixedElementDesiredHeights + stretChableElementsDesiredHeights;

        var outputSize = new Size(availableSize.Width, height);
        return outputSize;
    }

WPF Image Caching

I have a WPF application that takes a snapshot image from a video file. The user can define the timestamp from which to take the image. The image is then saved to a temporary location on disk, and is then rendered into an <image> element.

The user should then be able to select a different timestamp, which then overwrites the temporary file on disk - this should then be displayed within the <image> element.

Using Image.Source = null;, I can clear the image file from the <image> element, so it displays a blank space instead. However, if the source image file is then overwritten with a new image (with the same name) and loaded into the <image> element, it still shows the old image.

I am using the following logic:

// Overwrite temporary file file here

// Clear out the reference to the temporary image
Image_Preview.Source = null;

// Load in new image (same source file name)
Image = new BitmapImage();
Image.BeginInit();
Image.CacheOption = BitmapCacheOption.OnLoad;
Image.UriSource = new Uri(file);
Image.EndInit();
Image_Preview.Source = Image;

The image displayed in the <image> element does not change, even though the original file has been completely replaced. Is there an image caching issue here that I am not aware of?

Using timeline Control in my WPF application C#?

I have been trying to implement timeline in my WPF C# application. I have no prior know-how for doing this. I tried this tutorial

Its a good one. But I need to have an avanced timeline in my application. I dont seem to have any such controls under the ToolBox. I really need guidance on this. Thanks all

How to place buttons in a canvas dynamically so that it won't overlap each other?

I am writing an application in C#, WPF, Windows Phone 8.1 apps and I have one canvas in a 480x480 rectangular grid, and I want to put some buttons onto the canvas based on certain logic, there will be minimum 5 buttons and maximum 12-15 buttons, now based upon certain conditions I want to put buttons in the canvas so that it does not overlap with each other.

I started with Grid idea initially with number of rows and columns set and every row/column will have only one buttons, Suppose I have 6 buttons I will call this method CreateButtonsControls(3,3); but the way it placed the Buttons inside the grid it looks very monotonous to me.

private void CreateButtonsControls(int rows, int columns)
    {
        // Create a Grid
        Grid rootGrid = new Grid();

        // It will create columns
        createColumns(rootGrid, columns);

        // It will create rows
        createRow(rootGrid, rows);

        for (int i = 0; i < rows; i++)
        {
            for (int j = 0; j < columns; j++)
            {
                Button button = new Button();
                button.HorizontalAlignment = HorizontalAlignment.Right;
                button.VerticalAlignment = VerticalAlignment.Top;
                button.Margin = new Thickness(3);
                button.Width = 50;
                button.Height = 50;
                button.Content = "12";
                Grid.SetRow(button, i);
                Grid.SetColumn(button, j);
                rootGrid.Children.Add(button);
            }
        }
        // This will add the root grid to UI
        grdButton.Children.Add(rootGrid);

    }

and I thought to implement it in a canvas. I want that all the buttons will be placed inside the canvas scatter way. But I don't know how can I achieve this.

There is one property
Canvas.SetLeft(UIControl, positionX ) Canvas.SetTop(UIControl, positionY )

But How do I decide this positionX and positionY at runtime so that it doesnot overlap eachother, any idea or suggestions?

Thanks

Bind Radbutton in RadGridView to Icommand - WPF MVVM

Here is my Code. Can I use GridViewcolumn and datatemplate for this ? I want Radbutton in every row. Once I click on that button, I want to pass the row details to ICommand. How can I do this ?

XAML:

<telerik:GridViewColumn Width="100">
    <telerik:GridViewColumn.CellTemplate>
          <DataTemplate>

           </DataTemplate>
     </telerik:GridViewColumn.CellTemplate>
</telerik:GridViewColumn>

C#:

public ICommand ShowCommand
{
    get
    {
        return new RelayCommand(this.ShowDetails);
    }
}

Winforms combobox text

lets say I have combobox and I have set data source (string list) to it. I don't want to include - Select - to the list. is it possible to display - Select - on dropdown without adding it to datasource. (Is it possible to display text which is not in the list?)

WPF - DataGrid - change the selected item of only one combo box ( out of a list of comboboxes ) based on the selected item of some other combobox

This question is little bit similar to the question in WPF - change the selected Item of one combobox to the selected item of another combobox, but there is a difference. I have already made a comment in it and asked how to do this new change. But no one replied, that's why I thought of posting it as a new question. Please do not mark this as a duplicate of the previous one, because it is not.

I have the following in my viewmodel.

private <MyClass> _firstComboBoxSelection;
public <MyClass>  FirstComboboxSelection
{
     set { _firstComboBoxSelection=value; OnPropertyChanged("SecondComboboxSelection"); }
     get { return _firstComboBoxSelection ; }

}

 private <MyClass> _secondComboBoxSelection;
 public <MyClass>  SecondComboboxSelection
 {
     set { _secondComboBoxSelection=value; }
     get { return _secondComboBoxSelection ; }

 }

At the same time , I have a datagrid in my .xaml file.

  <DataGrid ItemSource="{Binding SomeData}">
       <DataGrid.Columns>
             <DataGridTemplateColumn>
                     <DataGridTemplateColumn.CellTemplate>
                         <DataTemplate>
                              <TextBlock Text="{Binding Name}"/> 
                         </DataTemplate>
                     </DataGridTemplateColumn.CellTemplate>
             </DataGridTemplateColumn>

             <DataGridTemplateColumn>
                     <DataGridTemplateColumn.CellTemplate>
                         <DataTemplate>
                             <ComboBox Name="cmbFirst"
                                               ItemSource="{Bnding SomeData_2}"  SelectedItem="{Binding FirstComboboxSelection}"/>
                         </DataTemplate>
                     </DataGridTemplateColumn.CellTemplate>
             </DataGridTemplateColumn>

             <DataGridTemplateColumn>
                      <DataGridTemplateColumn.CellTemplate>
                         <DataTemplate>
                                <ComboBox Name="cmbSecond"
                                       ItemSource="{Bnding SomeData_3}"  SelectedItem="{Binding SecondComboboxSelection}"/>
                         </DataTemplate>
                     </DataGridTemplateColumn.CellTemplate>
             </DataGridTemplateColumn>
      </DataGrid.Columns>
  </DataGrid>

What I want is to change the third column's combo box's selected item when second column's selected item is changed. This is a grid. So, this change should occur only in one row. That is if I change the selected item of second column's third row's combo box, then the value of third column's third row's combo box's selected item should be changed. Others should remain as it is.

But , according to what I have done in my view model, changing the selected item of second column's one specific row changes the third column's all rows' selected items. Can someone help me to fix this ?

protected void OnPropertyChanged(string propertyName)
    {
        PropertyChangedEventHandler handler = PropertyChanged;
        if (handler != null)
        {
            SecondComboboxSelection = SomeSampleData;

            handler(this, new PropertyChangedEventArgs(propertyName));
        }
    }

WPF event mystery

I am new in WPF and I am unable to understand this behavior of my code... I have a class of user control...

public class CustomControl1 : Control
{
    .... some code here ... 

    /// <summary>
    /// Constructor
    /// </summary>
    public CustomControl1()
    {
        // user items
        UserItems = new ObservableCollection<Label>();
        UserItems.CollectionChanged += UserItems_CollectionChanged;            
    }

    // informace o pridani do kolekce
    void UserItems_CollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
    {
        // !! ?? WHY IS THIS EVENT FIRED AFTER XAML SETS UserItems PROPERTY TO NEW INSTANCE ??  
    }

    /// <summary>
    /// User items
    /// </summary>
    public ObservableCollection<Label> UserItems
    {
        get { return (ObservableCollection<Label>)GetValue(UserItemsProperty); }
        set 
        {
            // XAML code sets this value with new instance of ObservableCollection !
            SetValue(UserItemsProperty, value);
        }
    }

    // Using a DependencyProperty as the backing store for UserItems.  This enables animation, styling, binding, etc...
    public static readonly DependencyProperty UserItemsProperty =
        DependencyProperty.Register("UserItems", typeof(ObservableCollection<Label>), typeof(CustomControl1), new UIPropertyMetadata(null));

}

I use this custom control in XAML window...

<Window
        xmlns="http://ift.tt/o66D3f"
        xmlns:x="http://ift.tt/mPTqtT"
        xmlns:c="clr-namespace:WpfCustomControlLibrary1;assembly=WpfCustomControlLibrary1" x:Class="WpfApplication1.MainWindow"
        Title="MainWindow" Height="350" Width="525">
    <Grid>
        <c:CustomControl1>
            <c:CustomControl1.UserItems>
                <Label>Menu1</Label>
                <Label>Menu2</Label>
            </c:CustomControl1.UserItems>
        </c:CustomControl1>
    </Grid>
</Window>

When I debug this code,

1) Constructor creates new instance of ObservableCollection and registers UserItems_CollectionChanged. to this instance.

2) UserItems property setter is raised and UserItems is set to a NEW INSTANCE of ObservableCollection. This instance should not have UserItems_CollectionChanged registered to it.

3) Event UserItems_CollectionChanged is fired for Menu1 and Menu2 labels. WHY? new instance of ObservableCollection should not raise this events !

There is something in this code or behind WPF what I do not understand. Can you help me ? Sorry for my bad English.

Event Triggers not working in Code Behind

I want create WPF controls at Runtime dynamically. In the below code, I have added StackPanel at XAML and crated Button/TextBlock/Triggers at code behind. I want to see TextBlock under button at MouseEnter action and want to hide TextBlock at MouseLeave action. This is not working as expected. If add Button/Textblock code at XAML (commented now) Instead of creating them at Code behind(un commented now) then it is working fine. Please let me know how to fix this? Not able understand why this not working If I create the button at runtime instead of XAML code. Thanks

XAML

<Grid>
   <StackPanel Name="stackPanel5" >
      <!--
      <Button Name="Button1" Cursor="Hand" Content="Press Me"/>
      <Border x:Name="TooltipBrd" BorderBrush="Black" BorderThickness="10,0,10,10" HorizontalAlignment="Center"  VerticalAlignment="Center"  Visibility="Collapsed">
         <TextBlock Margin="0,10,0,0" x:Name="myTextBlock" Text="Coded Test" />
      </Border>
      -->
   </StackPanel>
</Grid>

code

public void LoadData()
{
   //VisualState vs = new VisualState();
   //vs.SetValue(FrameworkElement.NameProperty, YourStateName);

   Button Button1 = new Button() { Cursor = Cursors.Hand, Content = "Press Me!" };
   stackPanel5.Children.Add(Button1);

   Border TooltipBrd = new Border()
   {
       BorderBrush = Brushes.Black,
       BorderThickness = new Thickness(10, 10, 10, 10),
       HorizontalAlignment = HorizontalAlignment.Center,
       VerticalAlignment = VerticalAlignment.Center,
       Visibility = Visibility.Collapsed
   };

   TextBlock txtB1 = new TextBlock() { Text = "Lakshman", Margin = new Thickness(0, 100, 0, 0) };
   TooltipBrd.Child = txtB1;

   stackPanel5.Children.Add(TooltipBrd);

   System.Windows.Interactivity.EventTrigger trigger1 = new System.Windows.Interactivity.EventTrigger();
   trigger1.EventName = "MouseEnter";

   ChangePropertyAction action1 = new ChangePropertyAction();
   action1.TargetName = "TooltipBrd";
   action1.PropertyName = "Visibility";
   action1.Value = Visibility.Visible;

   trigger1.Actions.Add(action1);
   trigger1.Attach(Button1);

   System.Windows.Interactivity.EventTrigger trigger2 = new System.Windows.Interactivity.EventTrigger();
   trigger2.EventName = "MouseLeave";

   ChangePropertyAction action2 = new ChangePropertyAction();
   action2.TargetName = "TooltipBrd";
   action2.PropertyName = "Visibility";
   action2.Value = Visibility.Collapsed;

   trigger2.Actions.Add(action2);
   trigger2.Attach(Button1);
}

Wpf RichTextBox execute command by sending programmatic key strokes

I need to send keystrokes to a RichTextBox which at the and should execute some commands like ToggleBold or SelectAll etc.

I call the following code in a loop to iterate through SomeEvent and SomeKey pairs.

PresentationSource presentationSource = PresentationSource.FromVisual(RichTextBoxControl);

if (presentationSource == null)
{
    return;
}

if(SomeEvent == KeyDownEvent)
{
    //InputManager.Current.ProcessInput(new KeyEventArgs(Keyboard.PrimaryDevice, presentationSource, 100, SomeKey) { RoutedEvent = PreviewKeyDownEvent });
    InputManager.Current.ProcessInput(new KeyEventArgs(Keyboard.PrimaryDevice, presentationSource, 100, SomeKey) { RoutedEvent = KeyDownEvent });
}
else if (SomeEvent == KeyUpEvent)
{
    //InputManager.Current.ProcessInput(new KeyEventArgs(Keyboard.PrimaryDevice, presentationSource, 100, SomeKey) { RoutedEvent = PreviewKeyUpEvent });
    InputManager.Current.ProcessInput(new KeyEventArgs(Keyboard.PrimaryDevice, presentationSource, 100, SomeKey) { RoutedEvent = KeyUpEvent });
}

For example to activate ToggleBold I call following pairs in a loop:

KeyDownEvent, Keys.Control
KeyDownEvent, Keys.B
KeyUpEvent, Keys.B
KeyUpEvent, Keys.Control

I have tried KeyDownEvent - KeyUpEvent, PreviewKeyDownEvent - PreviewKeyUpEvent, and PreviewKeyDownEvent - KeyDownEvent - PreviewKeyUpEvent - KeyUpEvent, but none of them worked.

The RichTextBox actually catches the events but it does not react to them. This is also the case if I send alphanumeric characters (They are not printed on RichTextBox). However if I send Keys.Back it actually recognizes and deletes a character from the text.

The solutions like SendKeys and keybd_event are not applicable since the program will be on the background while the keystrokes are sent.

Is there a way to send keystrokes to a control like they really are sent by the user?

Reading .txt file using FlowDocumentReader - WPF

In my main window when I click on the menu item, File --> Open and select the .txt file, it should be displayed using a Flow Document Reader in a new window. I have included the code below, but it doesn't work.

private void file_open(object sender, System.Windows.RoutedEventArgs e)
    {

        // Configure open file dialog box
Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog();
dlg.FileName = ""; // Default file name
dlg.DefaultExt = ".txt"; // Default file extension
dlg.Filter = "List Files (.txt)|*.txt"; // Filter files by extension    
dlg.InitialDirectory = @"D:\TextFiles\"; // Initial directory

// Show open file dialog box
Nullable<bool> result = dlg.ShowDialog();

// Process open file dialog box results 
if (result == true)
{
// Open document 
string filename = dlg.FileName;

// Open new window for displaying text file
var openwin = new Open_Window2();
openwin.Show();

// Read text file
string filename = dlg.FileName;

Paragraph paragraph = new Paragraph();
paragraph.Inlines.Add(System.IO.File.ReadAllText(filename));
FlowDocument document = new FlowDocument(paragraph);
FlowDocReader.Document = document; 

}

}

Bind a collection of a model to only a part of another collection

I have the requirement to select/map only a few of datasources for each of my applications, by first selecting the application on the left then the mapped/selected (few) datasources on the right (see screenshot).

I often have such a scenario as a business requirement, however I wasn't able to come up with a good solution to model this using WPF bindings.

Given the following code:

The models:

class DataSource
{
    public DataSource(string name)
    {
        Name = name;
    }

    public string Name { get; private set; }
}

class SoftwareSolution
{
    public SoftwareSolution(string name)
    {
        Name = name;
        this.DataSources = new ObservableCollection<DataSource>();
    }

    public string Name { get; private set; }
    public ObservableCollection<DataSource> DataSources { get; private set; }
}

class MainWindowViewModel
{
    public MainWindowViewModel()
    {
        this.SoftwareSolutions = new ObservableCollection<SoftwareSolution>();
        this.SoftwareSolutions.Add(new SoftwareSolution("Software 1"));
        this.SoftwareSolutions.Add(new SoftwareSolution("Software 2"));
        this.SoftwareSolutions.Add(new SoftwareSolution("Software 3"));

        this.AllAvailableDatasources = new ObservableCollection<DataSource>();
        this.AllAvailableDatasources.Add(new DataSource("SQL Server"));
        this.AllAvailableDatasources.Add(new DataSource("Oracle"));
        this.AllAvailableDatasources.Add(new DataSource("DB2"));
        this.AllAvailableDatasources.Add(new DataSource("MySQL"));
    }

    public ObservableCollection<DataSource> AllAvailableDatasources { get; private set; }
    public ObservableCollection<SoftwareSolution> SoftwareSolutions { get; private set; } 
}

XAML:

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

    <TextBlock Text="Application" />
    <ListBox Margin="0,25,5,0" VerticalAlignment="Stretch" ItemsSource="{Binding SoftwareSolutions}" DisplayMemberPath="Name" />

    <TextBlock Grid.Column="1" Text="DataSources" />
    <ListBox Grid.Column="1" Margin="0,25,0,0" VerticalAlignment="Stretch" ItemsSource="{Binding AllAvailableDatasources}">
        <ListBox.ItemTemplate>
            <DataTemplate>
                <DockPanel>
                    <CheckBox DockPanel.Dock="Left" />
                    <TextBlock DockPanel.Dock="Left" Text="{Binding Name}" Margin="5,0,0,0" />
                </DockPanel>
            </DataTemplate>
        </ListBox.ItemTemplate>
    </ListBox>
</Grid>

The GUI:

example gui

What pattern can I use to "bind" the checkboxes on the right to the selection on the right?

ItemContainerGenerator.Items in .NEt 4.0

I started a project using .NET 4.5, now I have to switch to .NET 4.0. Everything works fine, except the "Items"-Property of ItemContainerGenerator is missing. I use it to find the row of a DataGrid that starts with the letter of a typed key. The Code is:

     ReadOnlyCollection<object> rows = datagrid.ItemContainerGenerator.Items;
     datagrid.ScrollIntoView(rows[rows.Count - 1]);
     foreach (DataRowView row in rows)
     {
          string name = row.Row.ItemArray[0].ToString();
          if (name.StartsWith(keyChar + "", StringComparison.OrdinalIgnoreCase))
          {
               datagrid.ScrollIntoView(row);
               datagrid.UpdateLayout();
               return;
          }
     }

Note: When debugging, the "Items"-Property is present and filled.

Do you know a way to access the "Items"-Property or a workaround to get the same function without using the "Items"-Property? Any suggestions will be welcomed.

Load BitmapImage in background thread causes UI thread to stutter

I have a bit of code which loads a BitmapImage in the background, freezes it, and sends it off to the UI thread. However, even without sending to the UI thread, the act of loading a JPG into a BitmapImage causes the UI to stutter, even though it's happening on a background thread.

On reading about BitmapImage, it seems it might be the case that even if in a background thread, BitmapImage will use the Dispatcher and therefore run at least part of it's loading process in the UI thread.

This is pretty bad news for my animation capability, as it stutters and stalls on loading images in the background. As far as my code is concerned, the only bit to run in the UI thread is setting the 'Source' property on an Image to be the BitmapImage.

So, simple question, how can I load up a JPG into a BitmapImage without touching the UI thread?

List-box inside a list-box in C#

I have a list-box inside a list-box like this.

<ListBox x:Name="listBox1">
   <ListBox.ItemTemplate>
      <DataTemplate>
         <StackPanel>
            <StackPanel.Background>
               <SolidColorBrush Color="#FF2B3643" Opacity="1"/>
            </StackPanel.Background>
            <StackPanel>
               <TextBlock Text="{Binding X}"/>
               <TextBlock Text="{Binding Y}"/>
            </StackPanel>
            <Button Click="Button_Click">
            <ListBox x:Name="listBox2">
               <ListBox.ItemTemplate>
                  <DataTemplate>
                     <StackPanel>
                        <TextBlock Text="{Binding Name}"/>
                        <TextBlock Text="{Binding Number}"/>
                     </StackPanel>
                  </DataTemplate>
               </ListBox.ItemTemplate>
            </ListBox>
         </StackPanel>
      </DataTemplate>
   </ListBox.ItemTemplate>
</ListBox>

When I tried to bind the inner list-box, I wasn't able to do so.

The c# code that I tried is as follows.

List<Person> p = new List<Person>();

Person student = new Person();
student.Name = "Name1";
student.Number = "Number1";
p.Add(student);

Person teacher = new Person();
teacher.Name = "Name2";
teacher.Number = "Number2";
p.Add(teacher);

listBox2.ItemsSource = p; // cannot access listBox2

But I cannot access listBox2 from the xaml.cs code. It says listBox2 is not found. Also I want to bind the listBox2 only when the button is clicked and not when binding listBox1. Can someone tell me how do I access listBox2?

Get the ComboBox selected item in ComboBox_SelectionChanged method

I am following the MVVM pattern with C# and WPF. In my .xaml.cs file, I have a combobox_SelectionChanged method where I need to access the selected item of the combobox.

     var cb=sender as ComboBox;
     Type t=cd.getType();

I tried to get the type and then the object bound to SelectedItem property. That was not scuccessful.

Then I tried the following. ComboBoxItem cbi = (ComboBoxItem)cb.SelectedItem;

      string text = cbi.Content.ToString();

even that was not successful. Can someone suggest me a way to do that ?

Identify auto generated TextBox

I want to build a simple properties view where one can change each value.

The properties are grouped by one name like this:

  • name1: property1,property2
  • name2: property1,property2
  • ...

So I created a DataGrid with a template to fill the grid (note that I removed every style property etc. and the text values are also just examples):

<DataGrid>
    <DataGrid.Columns>
        <DataGridTemplateColumn Header="Property Group Name">
            <DataGridTemplateColumn.CellTemplate>
                <DataTemplate>
                    <TextBlock Text="{Binding propertyGroupName}" />
                </DataTemplate>
            </DataGridTemplateColumn.CellTemplate>
        </DataGridTemplateColumn>
        <DataGridTemplateColumn Header="Property 1">
            <DataGridTemplateColumn.CellTemplate>
                <DataTemplate>
                    <TextBox Text="{Binding property1}" />
                </DataTemplate>
            </DataGridTemplateColumn.CellTemplate>
        </DataGridTemplateColumn>
        <DataGridTemplateColumn Header="Property 2">
            <DataGridTemplateColumn.CellTemplate>
                <DataTemplate>
                    <TextBox Text="{Binding property2}" TextChanged="TextBox_TextChanged" />
                </DataTemplate>
            </DataGridTemplateColumn.CellTemplate>
        </DataGridTemplateColumn>
    </DataGrid.Columns>
</DataGrid>

As you can see I'm now trying to add a TextChanged event and there is my problem: Where do I get the propertyGroupName information from, since I only need to change the property2 from a specific propertyGroup.

I'm ready for any hint or solution... maybe the 'auto gen datagrid' isn't the best decision here?

WPF Datepicker SelectDateChanged event invoked as view model command not firing

I have A Datepicker control on a Grid that is bound with a Listbox through SelectedItem and the Listbox ItemsSource is a DataTable DefaultView. as shown below

<Grid Name="gridOfferte" DataContext="{Binding ElementName=lstOfferte, Path=SelectedItem}">
   <DatePicker Name="dtpkDataRevOff" Grid.Column="4"   
               SelectedDate="{Binding DataRevOffProperty, Mode=TwoWay}" >
       <i:Interaction.Triggers>
           <i:EventTrigger EventName="SelectedDateChanged">
               <i:InvokeCommandAction Command="{Binding       
                  Path=DatapickerSelectionCommand}" />
           </i:EventTrigger>
       </i:Interaction.Triggers>
   </DatePicker>
   ...
   ...

The DatapickerSelectionCommand doesn't fire. I noticed that the problem is that the Grid containing the Datepicker is bound to the Listbox. If I substitute the line

<Grid Name="gridOfferte" DataContext="{Binding ElementName=lstOfferte, Path=SelectedItem}">

with the line

<Grid Name="gridOfferte">

the DatapickerSelectionCommand fires. What could be the issue?

Thanh you for your support.

Conditional binding from view model to view in WPF using MVVM pattern

I am developing a WPF application using MVVM pattern. I have a combo in the view and two lists in the viewmodel (projects and organizations). Depending on the organizations list items I have to bind the the name of the organization or not. For example if the Count property of the organizations list is 1 the combobox item have to be "ProjectName", and if the Count property of the organizations list is greater than 1 the combobox item should look like "ProjectName - OrganizationName". This is the XAML code I have:

<ComboBox x:Name="textBox3" Grid.Row="2" Grid.Column="1" Grid.ColumnSpan="2" ItemsSource="{Binding Path=Projects}" DisplayMemberPath="Name" IsSynchronizedWithCurrentItem="True" SelectedItem="{Binding Path=SelectedProject}">
        </ComboBox>

How should I achieve this purpose. I hope for a little help. Cheers.

dimanche 10 mai 2015

Adapting grid with expanders to available height

I have a 'pile' of expanders on top of each other, which can be opened/closed independently.

All but one have a fixed height (when expanded). The other has a MinHeight, but I would like it to stretch to fill the remaining available height. If the combined heights of the expanders is greater than the available height, then scrollbars appear.

I've got that far using a Grid, with one expander per grid, and the row Height set to * for the stretching expander, and Auto for the others.

This works fine except in one case: if the stretchy expander is collapsed, and the combined height of the other expanders is less than the available height, then the stretching expander fills the remaining space anyway, just with it's content collapsed so I get a big blob of background colour.

I've also tried a StackPanel, or nested Grids, but haven't managed to resolve that problem without creating others.

Any ideas?

(Paste this into a Window)

<ScrollViewer>
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="*" MinHeight="23"/>
            <RowDefinition Height="Auto"/>
        </Grid.RowDefinitions>
        <Expander IsExpanded="False" Grid.Row="0" Header="Fixed">
            <Border Background="Red" Height="200" />
        </Expander>
        <Expander IsExpanded="False" Grid.Row="1" Header="Stretchy">
            <Border Background="Blue" />
        </Expander>
        <Expander IsExpanded="False" Grid.Row="2" Header="Fixed">
            <Border Background="Green" Height="300" />
        </Expander>
    </Grid>
</ScrollViewer>

Choosing developement technology: game engines,wpf or html5?

I am working on a project, where we want to use a camera to detect people and create an interactive experience like a touchscreen for advertisement. The goal is to have some cool and fascinating interactive animation and graphics(mostly 2D), but not a game.

We are using c# for the back end and are considering the following options: monogame, Ogre, WPF, unity, UDK, HTML5, webGL. which one do you think is the best option for us? Thanks,

ItemsControl (WrapPanel) Grouping should split GroupItems

I have a ItemsControl with a WrapPanel as ItemsHost and multiple Groupings. Got this going so far with the following Templates:

<GroupStyle.ContainerStyle>
   <Style TargetType="GroupItem">
      <Setter Property="Template">
         <Setter.Value>
            <ControlTemplate TargetType="GroupItem">
               <Grid>
                  <Grid.RowDefinitions>
                     <RowDefinition Height="Auto" />
                     <RowDefinition Height="*" />
                  </Grid.RowDefinitions>
                  <ContentPresenter Grid.Row="0" x:Name="PART_Header" Content="{TemplateBinding Content}" />
                  <ItemsPresenter Grid.Row="1" />
               </Grid>
            </ControlTemplate> 
         </Setter.Value>
      </Setter>
   </Style>
</GroupStyle.ContainerStyle>
<GroupStyle.Panel>
   <ItemsPanelTemplate>
      <WrapPanel IsItemsHost="True" Orientation="Vertical" />
   </ItemsPanelTemplate>
</GroupStyle.Panel>

Now I have the Problem that every Group does start a new Column why I want it to Continue right under the last GroupItem and Wrap in the Middle of the GroupItem instead of at the beginning.

It should look like the Windows 8 Apps overview (not the start page, if you go down to the overview)

Is that possible?

how to navigate between tabitem with Left and Right Key in WPF

hi everybody I want used shortcut key (using left and right key) in wpf and tabcontrol to navigation between tabitem I set code in Window_KeyDown(object sender, System.Windows.Input.KeyEventArgs e)

like this:

switch (e.Key)
            {
                case Key.Right:
                    if (tbControl.TabIndex == 0)
                        tbControl.TabIndex = 1;
                    break;

                case Key.Left:
                    if (tbControl.TabIndex == 0)
                        tbControl.TabIndex = 1;
                    break;
            }

but it's not do anything I want navigation between tabitem with left and right key thanks

How to free memory in WPF [on hold]

I have implemented WMP in my WPF app. It plays .mp4 file for me. My target system is Win XP with low configuration. I play .mp4 videos repeatedly on app. It works as I expected but after some time it stops working and black screen appears. I know its the problem of freeing WMP object from memory. Here in my case WMP object goes out of CLR scope that's why CLR is not able to free its object and memory dumps. Can you guys please give me some suggestion to release this object from memory so my app doesn't stop and works well. Thank you.