Affichage des articles dont le libellé est Active questions tagged wpf - Stack Overflow. Afficher tous les articles
Affichage des articles dont le libellé est Active questions tagged wpf - Stack Overflow. Afficher tous les articles

lundi 29 juin 2015

WPF- Bind tab selected/unselected event to method in tab viewmodel

I've got a ViewModel that holds a List of ViewModels that will be open as tabs by the view, and I want methods within the tab viewmodels to run when a tab gets selected/unselected. Currently I've got the TabControl in the view set up liek this:

<Window.Resources>
    <ResourceDictionary>
        <DataTemplate DataType="{x:Type VM1}">
            <View1 />
        </DataTemplate>
        <DataTemplate DataType="{x:Type VM2}">
            <View2 />
        </DataTemplate>
        <DataTemplate DataType="{x:Type VM3}">
            <View3 />
        </DataTemplate>

        <DataTemplate x:Key="TabItemTemplate">
            <Grid Width="Auto" Height="Auto">
                <ContentPresenter ContentSource="Header" Margin="3" 
                        Content="{Binding NiceName}"
                        HorizontalAlignment="Center" VerticalAlignment="Center">
                </ContentPresenter>
            </Grid>
        </DataTemplate>
    </ResourceDictionary>
</Window.Resources>

<TabControl Grid.IsSharedSizeScope="True" 
                SelectedIndex="{Binding CurrentTab, Mode=TwoWay}" 
                ItemsSource="{Binding Tabs}" 
                ItemTemplate="{StaticResource TabItemTemplate}" />

This all works fine, but I can't figure how to bind a tab change event to a methos within the tabbed viewmodels. You can change TabControl.SelectionChanged, but this would force the tabcontrol holding ViewModel to know what to call on it's tabs, forcing them to implement a specific interface. Is there any way to avoid this coupling in the tab holder ViewModel?

Multiple Inheritance - want to extend a class that extends Panel, but I also want to extend StackPanel

I have a control, ShrinkingTabPanel, that proportionally resizes tabs as they're added so they all fit (like Chrome). However, it extends Panel, and this doesn't work with the functionality I'm trying to achieve - the width of the ShrinkingTabPanel doesn't increase with number of items like it should.

When I changed the class to extend StackPanel instead, that was the exact functionality I needed.

However, ShrinkingTabPanel is a control that is part of a library that we bought, and it's usually discouraged to change imported source code.

I know multiple inheritance isn't allowed in C#, but is there any way I can "effectively" extend ShrinkingTabPanel and StackPanel in one class?

The first solution I thought of was to make a new class that extended StackPanel, and to just call ShrinkingTabPanel.ArrangeOverride() and ShrinkingTabPanel.MeasureOverride() within the respective methods, effectively extending ShrinkingTabPanel. But I'm not sure if that's the smartest idea.

Check ComboBox (Xceed WPF Toolkit), How to get short name to display from database?

This is my first post and I am a relative newbie regarding all things programming related. I hope you will be patient with me. I have a WPF application I am working on. My current issue is a Check ComboBox I am using. When I make selections out of the list that is pulled from a sqlite database file, the full name of the selection is displayed. I would like to change this and have a short name from the database appear in the ComboBox area while leaving the long descriptive name in the dropdown portion. I thought working with display and value member would help out, but have yet to get it working. I can get one or the other by changing the column index reference to my sqlite db. The ComboBox is a multi-select item and it needs to update as selections are made or cleared. Below is the bit of code I have that populates the ComboBox. I am unable to attach an image of the data due to low Rep numbers. Column 0 is the full descriptive name, Column 1 has the short name I am interested in displaying.

public void Fill_Modality()

        {
            SQLiteConnection sqliteCon = new SQLiteConnection(dbConnectionString);
            try
            {
                sqliteCon.Open();
                string Query = "Select * from Modality_list";

                SQLiteCommand createCommand = new SQLiteCommand(Query, sqliteCon);
                SQLiteDataReader dr = createCommand.ExecuteReader();
                while (dr.Read())
                {
                    string modname = dr.GetString(0);
                    Modality_Select.Items.Add(modname);
                }

                dr.Close();
                sqliteCon.Close();
            }
            catch (Exception ex)
            {
                System.Windows.MessageBox.Show(ex.Message);

            }
        }

Thank you for any help you may be able to provide.

Patrick

WPF (Vb.net): How to change the application icon dynamically?

I'm working on a simple application for Windows (if you ask, Windows Vista+ compatible) and I'd like the user to be able to change the icon of the application.

I have two icons, one old and one new, and I'd like the user to be able to go to Settings (for example) and check "Use old icon" or uncheck it, and depending on the chosen option the icon of the application - the shortcut desktop icon, the icon in the tray bar, the icon in the ALT+TAB menu, and so on - will change to the one chosen.

The application can make the change after it has been reopened (it's not important to show it immediatelly).

Is this possible? Or the only way is to set the icon through the project settings before compiling it?

Thanks for your help and time!

Multiple values selection in a desktop application

I was preparing a MS Access based Desktop Database Application for a Coaching classes. Now since previously the application only consisted of the basic form based functions including, adding new student, displaying the list of students, the fee structure and the attendance. Now he's asked me to prepare a more dynamic application, adding following functionalities along with the previous, 1. A question based contents, which can be selected at one time

eg: q1
 q2
 q3
 q4

So if we select q1 & q4, only those two questions should be displaying in the next sheet(wordsheet preferably).
Thus helping him to make a quick question paper.

I am not much familiar on how to achieve this on Ms Access. I tried Macros, but I couldn't find one which selects multiple questions and achieves the above task.
So i wanted to get an help on this, is there a way to achieve this on MS Access or is there some other technology which might help me on this?

WPF How to make a Viewbox aware of its available space from within a StackPanel

I have a custom WPF control based on Soroosh Davaee’s ImageButton example at http://ift.tt/T2BK1s. The custom control combines an Image and TextBlock in a horizontal StackPanel within a Button. (BTW, to get Soroosh’s example to run, I had to edit the solution properties so that “SampleView” is the startup project rather than “ExtendedButton” being the startup project.)

I want the text in the TextBlock to automatically shrink if necessary to avoid clipping at the right edge if the text is too long to fit naturally in the button. For example, if I edit Soroosh's MainWindow.xaml to make the button text too long to fit...

    ...
    <EB:ImageButton Width="100" Height="30" Content="TextTooLongToFitInTheButton" Grid.Row="2"
    ...
    <EB:ImageButton Width="100" Height="30" Content="TextTooLongToFitInTheButton" Grid.Row="2"
    ...

...the result is the following buttons with clipped text:

Buttons with clipped text

In researching this, it seems the simplest way to auto-shrink the content of a TextBlock is to wrap it within a Viewbox:

<Viewbox StretchDirection="DownOnly" Stretch="Fill">
    <TextBlock ... />
</Viewbox>

DownOnly apparently prevents the Viewbox from enlarging the text to fill the space, and Fill (as opposed to Uniform) seems to tell it to stretch (shrink) only the dimension that needs to shrink (i.e. the horizontal dimension in my case).

In Soroosh's example Generic.xaml file, I wrapped the TextBlock in such a Viewbox:

     <Button >
         <StackPanel Orientation="Horizontal">
             <Image Margin="2 0"
                    Source="{TemplateBinding Image}"
                    Width="{TemplateBinding ImageWidth}"
                    Height="{TemplateBinding ImageHeight}"
                    Visibility="{TemplateBinding Image,Converter={StaticResource VisibilityConvertor}}"
                    VerticalAlignment="Center"/>
I added-->   <Viewbox StretchDirection="DownOnly" Stretch="Fill">
             <TextBlock Text="{TemplateBinding Content}"
                    VerticalAlignment="Center"/>
I added-->   </Viewbox>
         </StackPanel>
     </Button>

This produced exactly the same clipped button text. Just experimenting, I tried forcing the Viewbox to have a fixed width...

             <Viewbox StretchDirection="DownOnly" Stretch="Fill" Width="60">

...which produced this:

Viewbox with manually-sized width

...which shows the capability of the Viewbox, if only it could somehow know its available width when it's inside the StackPanel.

I did note that if I wrap the Viewbox around the whole StackPanel, it successfully auto-shrinks the entire content of the StackPanel:

     <Button >
         <Viewbox StretchDirection="DownOnly" Stretch="Fill" Width="60">
             <StackPanel Orientation="Horizontal">
                 <Image Margin="2 0"
                    Source="{TemplateBinding Image}"
                    Width="{TemplateBinding ImageWidth}"
                    Height="{TemplateBinding ImageHeight}"
                    Visibility="{TemplateBinding Image,Converter={StaticResource VisibilityConvertor}}"
                    VerticalAlignment="Center"/>
                 <TextBlock Text="{TemplateBinding Content}"
                    VerticalAlignment="Center"/>
             </StackPanel>
         </Viewbox>
     </Button>

...which produces very nearly what I want:

Viewbox wrapping the entire StackPanel

...but both the image and text are shrunk, and I want only the text shrunk.

How can I make the Viewbox, wrapping only the TextBox, know its available width (and height, I suppose) from within a cell of the StackPanel?

WPF media kit camera orientation not working properly

I am developing a camera application for tablet PC running Windows 8.1 using wpf mediakit. I am using VideoCapture for this,

<Controls:VideoCaptureElement 
                    FPS="30"
                    x:Name="videoElement" Stretch="UniformToFill" 
                    HorizontalAlignment="Center"

                    VerticalAlignment="Center"
                    Height="Auto"
                    Width="Auto"
                    Margin="0, 0, 0, 0"
                    EnableSampleGrabbing="True"
                    Visibility="Visible"
                    UseYuv="False"
                    UseStillPin="False"
                    UnloadedBehavior="Close" >
                    <Controls:VideoCaptureElement.LayoutTransform>
                        <RotateTransform Angle="0" />
                    </Controls:VideoCaptureElement.LayoutTransform>
                </Controls:VideoCaptureElement>

The problem is that, when I change the orientation, the camera is not changing accordingly.

ie, If I am in a portrait view, the camera preview will be flipped.

How can I rotate the preview whenever the user changes the orientation ?

Tab Control without a line when selected

I want to show Tab control in WPF without using a line. My code as follows:-

            <TabItem Header="Tab 0">
            <TabItem.Style>
                <Style TargetType="{x:Type TabItem}">
                    <Setter Property="Template">
                        <Setter.Value>
                            <ControlTemplate TargetType="{x:Type TabItem}">
                                <Grid>
                                    <Border  Name="Border" Margin="0,0,0,0" BorderBrush="Gray">
                                        <ContentPresenter x:Name="ContentSite" VerticalAlignment="Center" HorizontalAlignment="Center" ContentSource="Header" Margin="12,2,12,2" RecognizesAccessKey="True"/>
                                    </Border>
                                </Grid>
                                <ControlTemplate.Triggers>

                                    <Trigger Property="IsSelected" Value="True">
                                        <Setter Property="Panel.ZIndex" Value="100" />
                                        <Setter TargetName="Border" Property="Background" Value="White" />
                                        <Setter TargetName="Border" Property="BorderThickness" Value="1,1,1,0" />
                                    </Trigger>

                                    <Trigger Property="IsSelected" Value="False">
                                        <Setter TargetName="Border" Property="Background" Value="#DDDDDD" />
                                        <Setter TargetName="Border" Property="BorderThickness" Value="1,1,1,0" />
                                    </Trigger>
                                    <Trigger Property="IsMouseOver" Value="True">
                                        <Setter TargetName="Border" Property="Background" Value="White" />
                                        <Setter TargetName="Border" Property="BorderThickness" Value="1,1,1,0" />
                                    </Trigger>

                                </ControlTemplate.Triggers>
                            </ControlTemplate>
                        </Setter.Value>
                    </Setter>
                </Style>
            </TabItem.Style>

            <Grid Background="White" />
        </TabItem>

When I don't use style <TabItem.Style> Tab is coming without Line as per my requirement, but I need to use <TabItem.Style> because of the requirement.

Please help.

Thanks

Show Notification in Wpf

I want to show a grid that involve a label and I want to show this in left-above of another grid.the wpf code(xml) is this :

<Grid.Triggers>
            <EventTrigger RoutedEvent="FrameworkElement.Loaded">
                <BeginStoryboard>
                    <Storyboard>
                        <DoubleAnimationUsingKeyFrames Storyboard.TargetProperty="(UIElement.RenderTransform).(ScaleTransform.ScaleY)" >
                            <SplineDoubleKeyFrame KeyTime="0:0:0" Value="0"/>
                            <SplineDoubleKeyFrame KeyTime="0:0:0.5" Value="1"/>
                        </DoubleAnimationUsingKeyFrames>
                        <DoubleAnimationUsingKeyFrames Storyboard.TargetProperty="(UIElement.Opacity)">
                            <SplineDoubleKeyFrame KeyTime="0:0:2" Value="1"/>
                            <SplineDoubleKeyFrame KeyTime="0:0:5" Value="0"/>
                        </DoubleAnimationUsingKeyFrames>
                    </Storyboard>
                </BeginStoryboard>
            </EventTrigger>
        </Grid.Triggers>
        <Grid.RenderTransform>
        <ScaleTransform ScaleY="1" />

</Grid>

How to create this notification when press a button? I have the C# code for this. thanks.

WPF Drag an email item from desktop

I am trying to drag an email into wpf canvas but not getting any solution. I can able to do drag and drop an email with attachments using Outlook data object by FileDescriptorW format.

My application color look with lines when

Please see this screenshot:

enter image description here

As you can see there is several 'lines' around my application Background, this when i connect to the machine that running my application using Remote Desktop or Radmin.

This is when i am running my application on my local machine:

enter image description here

Any suggestions how to avoid this behavior ?

Validating POCO / VM class

I have an MVVM project which is hooked up to EF6 (Database First). I would like to use Data Annotations to take care of the validation, do I need to create a public properties on the VM to represent each field in the POCO class or do I add it to the POCO class directly (when the database is updated I will surely have to go through the process again or is there a way of separating this additional validation?)

ListView Binding from List

I search over all internet but I didnt find an answer. I am new in MVVM and also pretty new in WPF :) So sorry for my lack of knowledge

I have defined method in one class where I search for USB devices (with help of another .dll library):

public void FindDevices()
    {
        _deviceList = HidDevices.Enumerate(VendorID, ProductID).ToArray();

        String[] deviceSNstring = new String[_deviceList.Length];
        String[] deviceManufacturerstring = new String[_deviceList.Length];
        String[] deviceProductstring = new String[_deviceList.Length];

        List<Devices> devices = new List<Devices>();

An later I become a nice List of devices.

In another class I want to bind this List in ViewModel class into ListView. How to do it? And I must Also start method to find my devices "FindDevices" :)

Command doesn't work on top level MenuItem in MVVM

It works fine if the MenuItem doesn't have a sub MenuItem, like this:

<MenuItem Header = "Open" Command="{Binding OpenCommand}"/>

but, when I add a sub MenuItem to it, the Command doesn't work:

<MenuItem Header = "Open" Command="{Binding OpenCommand}">
    <MenuItem />
</MenuItem>

I know I can add the Command to the header as a remedy:

<MenuItem>
    <MenuItem.Header>
        <Button Content = "Open" Command="{Binding OpenCommand}"/>
    </MenuItem.Header>
    <MenuItem/>
</MenuItem>

but is there a elegant way to fix it? any help will be appreciate.

WPF DataGrid Row Background Color depending of Last Cell of the Row

So for the better understanding. I have 2 SQL DataTables (server and client) and put them together into one DataGrid. Before i put the DataTables into the DataGrid, i added a column with a number, so that i can later see from which DataTable the row comes from. Now i wanted to change the background of the row depending of which DataTable it comes from.

My plan was:

-Use the number of the column i added at the end of the row to decide which color to use for the row.

But my problem:

  • How can i get the Data of the last cell of the row in wpf?
  • Can i just delete the Column after finishing this process?
  • And will the Color stay, even after sorting the rows afterwards?

Sorry, but i just cant get the Data of the specific cells....

Is there maybe a better way to do all of this?

Thank you for your Help!!!!

MUI: Modify appearance of back button

How can I easily override the styling of the back button. It's currently buried in ModernWindow.xaml, and I'd prefer not to compile in all of MUI into my solution.

<!-- back button -->
<controls:ModernButton Margin="8,10,0,0" HorizontalAlignment="Left" VerticalAlignment="Top"
                       EllipseDiameter="24" IconWidth="12" IconHeight="12"
                       IconData="F1 M 33,22L 33,26L 19.75,26L 27,33L 20.5,33L 11,24L 20.5,15L 27,15L 19.75,22L 33,22 Z"
                       Command="NavigationCommands.BrowseBack"
                       CommandTarget="{Binding ElementName=ContentFrame}" 
                       ToolTip="{x:Static modernui:Resources.Back}"
                       WindowChrome.IsHitTestVisibleInChrome="True" />

I just want to make it a little bigger and give it a background color of the current highlight color (i.e. blue).

I have a request to make it look more like the huge blue back button in Internet Explorer.

enter image description here

When Tooltip.Content gets populated?

I need to use the Tooltip.Content information of any given control.

Lets say there is a a control TextBlock and it is bound to a Tooltip. I access the Tooltip of the TextBlock by var toolTip=(ToolTip)TextBlock.ToolTip. The value of toolTip.Content remains null, but if I do a mouse hover over the control it is populated with the desired value.

How do I get the tooltip to populate its content before triggering a mouse over the control? Does the Tooltip loads its content lazily or is there something I am missing?

Bring MainWindow to front, not always on top, and wait for it to close

I have a WPF application with a single window. When the application starts, I want to bring it to the front. I also want to let the user move other windows on top of it (it shouldn't be always on top), and I want to wait for the window to close in code. Perhaps I am being too picky as WPF does not appear to support this.

Currently, I have this:

MainWindow.Topmost = true;
MainWindow.Show();
MainWindow.Activate();
MainWindow.Topmost = false;
MainWindow.Focus();

It's great except that MainWindow.Show() returns immediately and execution resumes. In the past, we were using

MainWindow.TopMost = true;
MainWindow.ShowDialog();

But then this window is always on top and obstructs all other windows (not the best user experience). Are there any other options? Please feel free to suggest I am architecting this incorrectly as well. Thank you!

Why my UserControl with a template of a Path is not properly clickable?

I created a class derived from UserControl, directly on code (without XAML), and defined a ControlTemplate in a ResourceDictionary. This control template is a pair of ellipses, as follows:

<ControlTemplate x:Key="MusclePositionControlTemplate" TargetType="{x:Type local:MusclePositionControl}">
    <ControlTemplate.Resources>
        <EllipseGeometry x:Key="bolinha" RadiusX="{StaticResource radius}" RadiusY="{StaticResource radius}">
            <EllipseGeometry.Center>
                <Point X="0" Y="{StaticResource distance}"/>
            </EllipseGeometry.Center>
        </EllipseGeometry>                      
    </ControlTemplate.Resources>
        <Path Fill="#9900ffff" StrokeThickness="1" Stroke="Black">
            <Path.Data>
                <GeometryGroup>
                    <StaticResource ResourceKey="bolinha"/>
                    <GeometryGroup>
                        <GeometryGroup.Transform>
                            <ScaleTransform ScaleY="-1"/>
                        </GeometryGroup.Transform>
                        <StaticResource ResourceKey="bolinha"/>
                    </GeometryGroup>
                </GeometryGroup>                                
            </Path.Data>        
            <Path.RenderTransform>
                <TransformGroup>
                    <RotateTransform Angle="{Binding Angle, RelativeSource={RelativeSource Mode=TemplatedParent}}"/>
                    <TranslateTransform
                        X="{Binding X, RelativeSource={RelativeSource Mode=TemplatedParent}}"
                        Y="{Binding Y, RelativeSource={RelativeSource Mode=TemplatedParent}}"/>
                </TransformGroup>               
            </Path.RenderTransform>
        </Path>
</ControlTemplate>

When I edit this template in Blend, I can select the path clicking on it, and it displays its outlines like this:

enter image description here

But when I add the actual control to a canvas, with its X, Y and Angle properties set to some value, the control renders itself fine, but its defining geometry keeps being that of a rectangle at the origin, and this affects hit testing (I cannot select at design time, or click at runtime, by clicking at the shape itself):

enter image description here

So my questions are:

  1. How should I create a ControlTemplate using a Path as "root" visual element, so that the clickable area of the control is that Path?
  2. Assuming a Path should not or could not be used as root visual for a ControlTemplate, how should I achieve the same end result?

How to create WAV header file for kinect v2.0 audio source?

I collect kinect audio frame in a byte array. how to create wav header file for this byte array that provided by kinect? i see and use http://ift.tt/1GKJnv7 ,but after the file is saved, file has a capacity and duration but audio not recorded.