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

Accessing an ancestor's property from within another control

$
0
0

I have a UserControl with a boolean property named ShowLegend. I can bind to that property just fine in the UserControl, like so...

<CheckBox Content="Show Legend" IsChecked="{Binding Path=ShowLegend, RelativeSource={RelativeSource AncestorType=UserControl}}" />

But when I try to bind to that property from within another control, I can't seem to access it. Like this...

<!-- Works --><CheckBox Content="Show Legend" IsChecked="{Binding Path=ShowLegend, RelativeSource={RelativeSource AncestorType=UserControl}}" /><!-- Doesn't Work --><sci:SciChartSurface><sci:SciChartSurface.ChartModifier><sci:ModifierGroup><sci:LegendModifier ShowLegend="{Binding Path=ShowLegend, RelativeSource={RelativeSource AncestorType={x:Type UserControl}}}" /></sci:ModifierGroup></sci:SciChartSurface.ChartModifier></sci:SciChartSurface>

Any ideas on how I need to structure the RelativeSource path? Thanks!


How to draw complex shape in c# wpf ?

$
0
0

Could someone draw 2 shapes in 2 sides like in picture that in red color ?

I try to draw but I do not know how to draw it. I just draw a Rectangle in center.

public partial class UserControl1 : UserControl
    {
        public UserControl1 ()
        {
            InitializeComponent ();
        }

        protected override void OnRender (DrawingContext drawingContext)
        {
            var centerX = 200;
            var centerY = 200;
            var pointCenter = new Point (centerX, centerY);
            var radius = 70;
            var pointsRadius = 2;
            var height = 20;
            var pen = new Pen (Brushes.Black, 1);
            var brush = Brushes.LightGray;

            var rectangle = new Rect (pointCenter.X - (radius / 2), pointCenter.Y - (height / 2), radius, height);
            drawingContext.DrawRectangle (brush, pen, rectangle);

            // dot in center
            drawingContext.PushTransform (new RotateTransform (90, pointCenter.X, pointCenter.Y));
            drawingContext.DrawEllipse (Brushes.Red, pen, pointCenter, pointsRadius / 2, pointsRadius);
            drawingContext.Pop ();



            base.OnRender (drawingContext);
        }
    }

someone can help me. Thanks

Maintain three values in collection

$
0
0
I am developing a WPF application in MVVM architecture. So I have many ViewModels and views in my project. For easy page navigation purpose, created a custom navigation services class and by passing viewmodel or view name I need to get other.
below method will call at starup.

private static void ConfigureNavigation()
{
	Uri test = new Uri("../Views/LoginView.xaml", UriKind.Relative); // I don't know how to pass to dictonary.
	NavigationService.Register<LoginViewModel, LoginView>();
	NavigationService.Register<MaintainerViewModel, MaintainerView>();
}

below code is the register method of navigation service

private static readonly ConcurrentDictionary<Type, Type> ViewModelMap = new ConcurrentDictionary<Type, Type>();
public static void Register<TViewModel, TView>() where TView : Page
{
	if (!ViewModelMap.TryAdd(typeof(TViewModel), typeof(TView)))
	{
		throw new InvalidOperationException($"ViewModel already registered '{typeof(TViewModel).FullName}'");
	}
}

Requirement 1
I need to navigate the frame to specified url using viewmodel..

Frame.Navigate(GetView(viewModelType), UriKind.Relative);

public static Uri GetView(Type viewModel)
{
	if (ViewModelMap.TryGetValue(viewModel, out Type view))
	{
		return;  Here I need to return url, which is registered in the register method;
	}
	throw new InvalidOperationException($"View not registered for ViewModel '{viewModel.FullName}'");
}

By passing viewmodel I need to get view and url..

Requirement 2
I need to get the viewmodel by using view name..

public static Type GetViewModel(Type view)
{
	var type = ViewModelMap.Where(r => r.Value == view).Select(r => r.Key).FirstOrDefault();
	if (type == null)
	{
		throw new InvalidOperationException($"View not registered for ViewModel '{view.FullName}'");
	}
	return type;
}

By passing view I need to get view.
By passing view I need to get viewmodel.

how to pass Uri from the ConfigureNavigation() to navigation service and don't know how to get from dictionary. The only problem is passing Uri.

any help..
How to pass uri to Register() method and get in GetView() method



Force a UserControl's width to stretch to parent container width...

$
0
0

I'm struggling with getting a UserControl I have created to stretch to it's parent container's full width.  I've tried the horizontalalignment stuff from xaml, and a few other things but nothing seems to work. 

 

My basic premise is I have a control that's a ListBox ... and then I have a custom UserControl which acts as an individual item in the ListBox.  I add a few of these items to the ListBox control in code.  The ListBox control stretches fine to the window's width, but it's items (my custom UserControl items) are not stretching ... they seem to have an arbitrary size depending on the data.

 

Is there some way to force the usercontrol items to stretch to their parent's width?

Render FrameworkElement without outside WPF application

$
0
0

We have a Class, written in F# which is basically a FrameworkElement. Internal there is a VisualCollection which holds the rendered parts - for compositioning i guess. 

The class itself represent a Graphic-To-Be-Rendered, which in this special case, has to be done without a UI thread and outside of a WPF application. 

What we do is the following:

  1. Spawn an STA Thread
  2. - Instantiate the Graphics
  3. - Populate with Data
  4. - Render to Bitmap
  5. - Return Synchronized stream
  6. Outside the STA Thread
  7. - Write stream to File

The file is empty but has the correct width & length. 

I believe that it is not possible to do this without an App() or a WPF Context of some kind. We're kind of at a loss here. 

Any Suggestions are welcome, since i've got nothing a the moment. The goal is basically to render something WPF into a FileStream from withing a thread inside a console application. 

How to group datagrid like multi-level tree in WPF

$
0
0

Hi,

I have a task to group data in DataGrid like a tree as following mockup:

Does anybody know to write the GroupStyle? Thanks.

Exporting canvas with transparent background and in bigger resolution than screen is. WPF c#

$
0
0
How can I export graphics on canvas with transparent background and in bigger resolution than screen is (screen is FHD and I want it in 4K and probbably be able to 8K)? Thanks

WPF and MVVM ?

$
0
0
I'm starting with WPF and MVVM from Windows Forms Apps. I have to admit that has been confusing. I have big doubts about all this platform and how to face it. But my question is: All the WPF apps are managed by paging? There's not multiple windows management?

How to compare two images and highlight the difference in red colour by creating a third image

$
0
0

Hi All,

I want to create a small project using Windows forms. There will be few images in two folders. I want to browse the folders using folder browse control and when I click the 'Compare' button on the form then it will start comparing all the images one by one in both the folders and generate images in a third folder and will also highlight the differences in Red colour. 

Regards


UWP app with fixed size

$
0
0

How to make the height/width (size) of a UWP app fixed?

I don't want to enlarge or reduce the size of UI during runtime.


Scale on condition

$
0
0

Hi,

I have this structure in place for now:

<ItemsControl.ItemsPanel><ItemsPanelTemplate><WrapPanel MaxWidth="500"
                           Height="85"
                           ClipToBounds="False" /></ItemsPanelTemplate></ItemsControl.ItemsPanel><ItemsControl.ItemTemplate><DataTemplate><Canvas  Width="95"
                         Height="70"><StackPanel Orientation="Vertical"                                                                                                
                                ClipToBounds="False"
                                RenderOptions.BitmapScalingMode="NearestNeighbor"
                                RenderTransformOrigin="0.5,0.5"
                                Width="95"><StackPanel.RenderTransform><ScaleTransform /></StackPanel.RenderTransform><StackPanel.Triggers><EventTrigger RoutedEvent="Mouse.MouseEnter"><EventTrigger.Actions><BeginStoryboard Name="ExpandText"><Storyboard><DoubleAnimation
                                                    Storyboard.TargetProperty="RenderTransform.ScaleX"
                                                             To="1.3"
                                                             Duration="0:0:0.2" /><DoubleAnimation
                                                    Storyboard.TargetProperty="RenderTransform.ScaleY"
                                                             To="1.3"
                                                             Duration="0:0:0.2" /></Storyboard></BeginStoryboard></EventTrigger.Actions></EventTrigger><EventTrigger RoutedEvent="Mouse.MouseLeave"><EventTrigger.Actions><BeginStoryboard Name="NormalText"><Storyboard><DoubleAnimation
                                                    Storyboard.TargetProperty="RenderTransform.ScaleX"
                                                             To="1"
                                                             Duration="0:0:0.2" /><DoubleAnimation
                                                    Storyboard.TargetProperty="RenderTransform.ScaleY"
                                                             To="1"
                                                             Duration="0:0:0.2" /></Storyboard></BeginStoryboard></EventTrigger.Actions></EventTrigger></StackPanel.Triggers><Border Name="MyBorder"
                                Margin="10,10,10,10"
                                Height="35"
                                ClipToBounds="False"
                                Width="75"                                                                                                
                                CornerRadius="5">                                                                                               ><Grid HorizontalAlignment="Stretch"
                                  ClipToBounds="False"
                                  VerticalAlignment="Stretch"><Button HorizontalAlignment="Stretch"
                                                    Height="30"
                                                    Margin="3"                                                                                                                   
                                                    IsEnabled="True"
                                                    Focusable="False"                                                                                                                    /><TextBlock FontSize="20"
                                           FontFamily="Verdana"
                                           Margin="0"                                                                                                           
                                           HorizontalAlignment="Center"
                                           VerticalAlignment="Center"
                                           TextTrimming="CharacterEllipsis"                                                                                                           
                                           IsHitTestVisible="False" /></Grid></Border><TextBlock TextTrimming="CharacterEllipsis"
                                   HorizontalAlignment="Center"/></StackPanel></Canvas></DataTemplate></ItemsControl.ItemTemplate>

Right now the buttons scale when I move the mouse on them but

What I want:

1. When I shrink the window the items in the wrap panel should first start wrapping.

2. Once they reach a certain size, they should start shrinking due to the view box.

3. Scaling on mouse over should work only when they shrink to a certain size.

Can anyone help me out.

Thank you.


Please Mark as Answered if this answers your question Or UnMark as Answered if it did not. Happy to Help :)

Unable to print the Xaml files using PrintDocument class in silver light, All of a sudden it started printing some of the pages Blank.

$
0
0

Hi All,

We have silver light app which is having a print functionality.

Print functionality is implemented  System.Windows.Printing.PrintDocument class provided to implement the printing in silver Light applications.

We are having a around 100 pages that gets printed based on selection. All the xaml pages are derived from Usercontrols having the formatted text content or a png image as the content.

This is a good working code. All of a sudden it's stopped working. It's printing the pages with some blank pages. We are not getting any exception. But when we are trying to print the pages to PDF. We are not getting the save option.

Below are the print settings that we are using.

                    

            PrinterFallbackSettings settings = new PrinterFallbackSettings();
            settings.ForceVector = true;
            settings.OpacityThreshold = 0.5;

                pd.Print("My Map");

     

 public void PD_PrintPage(object sender, PrintPageEventArgs e)
        {

            if (printCount < this.printObjects.Count)
            {
                if (this.printObjects != null && this.printObjects[printCount].PrintPages.Count > 0)
                {
                    e.PageVisual = (StackPanel)(VisualTreeHelper.GetParent((UserControl)this.printObjects[printCount].PrintPages[0]));
                    e.HasMorePages = true;
                }
                else
                {
                    e.HasMorePages = false;
                }
            }
        printCount++;
        }

Someone please share your inputs. As we are clueless on where we are going wrong. 

Thanks in advance 

Pratap G

1903 resize wpf windows issue

$
0
0

After 1903 update (Windows 10 Pro) there is a problem when resizing or moving a WPF window. When the mouse gets outside the window it stops moving/resizing until the mouse button is released or mouse gets inside window again. It's like the mouse capture isn't working and events stops firing.

Is there a fix to this issue?

Better description from another user here:

https://stackoverflow.com/questions/56354510/why-all-my-wpf-applications-fail-to-drag-outside-of-their-windows-since-windows/56847374#56847374

Non-reproducible Style.Seal() issue. (Last Resort)

$
0
0

Ok, so here's the deal.

I've been Googling for two weeks , to no avail. This post is kind of against all regulations, since i see everyone asking for code samples that make the issue reproducible.
Well that is impossible for my case...

In our company we're remodelling our application from winforms to WPF, and to have a neat layout we're using MaterialdesignInXAML toolkit (https://github.com/MaterialDesignInXAML/) , and MahApps (https://mahapps.com/).
(These are not hyperlinks because msdn won't allow me, or something like that...)

In one solution of our application, a weird thing happens. The solution builds fine. Two weeks ago, it ran perfectly too.
So , nothing changed since then, and i mean literally NOTHING. We use source control, so i actually made sure i had the EXACT same source code as two weeks ago. But, alas, the solution no longer runs...

On my computer that is. All my colleagues have tried and could run perfectly, not a single issue...
My stacktrace:

Unhandled Exception: System.Windows.Markup.XamlParseException: Initialization of 'MahApps.Metro.Controls.MetroThumbContentControl' threw an exception. ---> System.InvalidOperationException: Can only base on a Style with target type that is base type 'MetroThumbContentControl'.
   at System.Windows.Style.Seal()
   at System.Windows.StyleHelper.SealIfSealable(Object value)
   at System.Windows.ResourceDictionary.SealValue(Object value)
   at System.Windows.ResourceDictionary.OnGettingValue(Object key, Object& value, Boolean& canCache)
   at System.Windows.ResourceDictionary.OnGettingValuePrivate(Object key, Object& value, Boolean& canCache)
   at System.Windows.ResourceDictionary.GetValueWithoutLock(Object key, Boolean& canCache)
   at System.Windows.ResourceDictionary.GetValue(Object key, Boolean& canCache)
   at System.Windows.SystemResources.LookupResourceInDictionary(ResourceDictionary dictionary, Object key, Boolean allowDeferredResourceReference, Boolean mustReturnDeferredResourceReference, Boolean& canCache)
   at System.Windows.SystemResources.FindDictionaryResource(Object key, Type typeKey, ResourceKey resourceKey, Boolean isTraceEnabled, Boolean allowDeferredResourceReference, Boolean mustReturnDeferredResourceReference, Boolean& canCache)
   at System.Windows.SystemResources.FindResourceInternal(Object key, Boolean allowDeferredResourceReference, Boolean mustReturnDeferredResourceReference)
   at System.Windows.StyleHelper.GetThemeStyle(FrameworkElement fe, FrameworkContentElement fce)
   at System.Windows.FrameworkElement.UpdateThemeStyleProperty()
   at System.Windows.FrameworkElement.OnInitialized(EventArgs e)
   at System.Windows.FrameworkElement.TryFireInitialized()
   at MS.Internal.Xaml.Runtime.ClrObjectRuntime.InitializationGuard(XamlType xamlType, Object obj, Boolean begin)
   --- End of inner exception stack trace ---
   at System.Windows.Markup.XamlReader.RewrapException(Exception e, IXamlLineInfo lineInfo, Uri baseUri)
   at System.Windows.FrameworkTemplate.LoadTemplateXaml(XamlReader templateReader, XamlObjectWriter currentWriter)
   at System.Windows.FrameworkTemplate.LoadTemplateXaml(XamlObjectWriter objectWriter)
   at System.Windows.FrameworkTemplate.LoadOptimizedTemplateContent(DependencyObject container, IComponentConnector componentConnector, IStyleConnector styleConnector, List`1 affectedChildren, UncommonField`1 templatedNonFeChildrenField)
   at System.Windows.FrameworkTemplate.LoadContent(DependencyObject container, List`1 affectedChildren)
   at System.Windows.StyleHelper.ApplyTemplateContent(UncommonField`1 dataField, DependencyObject container, FrameworkElementFactory templateRoot, Int32 lastChildIndex, HybridDictionary childIndexFromChildID, FrameworkTemplate frameworkTemplate)
   at System.Windows.FrameworkTemplate.ApplyTemplateContent(UncommonField`1 templateDataField, FrameworkElement container)
   at System.Windows.FrameworkElement.ApplyTemplate()
   at System.Windows.FrameworkElement.MeasureCore(Size availableSize)
   at System.Windows.UIElement.Measure(Size availableSize)
   at System.Windows.Interop.HwndSource.SetLayoutSize()
   at System.Windows.Interop.HwndSource.set_RootVisualInternal(Visual value)
   at System.Windows.Window.SetRootVisual()
   at System.Windows.Window.SetRootVisualAndUpdateSTC()
   at System.Windows.Window.SetupInitialState(Double requestedTop, Double requestedLeft, Double requestedWidth, Double requestedHeight)
   at System.Windows.Window.CreateSourceWindow(Boolean duringShow)
   at System.Windows.Window.ShowHelper(Object booleanBox)
   at System.Windows.Threading.ExceptionWrapper.InternalRealCall(Delegate callback, Object args, Int32 numArgs)
   at System.Windows.Threading.ExceptionWrapper.TryCatchWhen(Object source, Delegate callback, Object args, Int32 numArgs, Delegate catchHandler)
   at System.Windows.Threading.DispatcherOperation.InvokeImpl()
   at MS.Internal.CulturePreservingExecutionContext.CallbackWrapper(Object obj)
   at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
   at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
   at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
   at MS.Internal.CulturePreservingExecutionContext.Run(CulturePreservingExecutionContext executionContext, ContextCallback callback, Object state)
   at System.Windows.Threading.DispatcherOperation.Invoke()
   at System.Windows.Threading.Dispatcher.ProcessQueue()
   at System.Windows.Threading.Dispatcher.WndProcHook(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 System.Windows.Threading.ExceptionWrapper.TryCatchWhen(Object source, Delegate callback, Object args, Int32 numArgs, Delegate catchHandler)
   at System.Windows.Threading.Dispatcher.LegacyInvokeImpl(DispatcherPriority priority, TimeSpan timeout, Delegate method, Object args, Int32 numArgs)
   at MS.Win32.HwndSubclass.SubclassWndProc(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam)
   at MS.Win32.UnsafeNativeMethods.DispatchMessage(MSG& msg)
   at System.Windows.Threading.Dispatcher.PushFrameImpl(DispatcherFrame frame)
   at System.Windows.Application.RunDispatcher(Object ignore)
   at System.Windows.Application.RunInternal(Window window)
   at <ApplicationName>.<SolutionName>.WPF.TestApp.App.Main()

What i have tried (in order):
Make sure windows updates were correctly installed.
Remove any unnecessary extensions/plugins from vs.
Make sure VS versions of my colleages are the same as mine.
Make sure VS installation is identical to my colleages'.
Clear the source control cache , and perform a pull of the code.
Delete the working folder on my computer , clear the source control cache, and pull.
Clear the visual studio cache, reset user preferences/settings, delete working folder, clear source control cache, and pull.

So basically, i've done almost anything within my knowledge, except the following three:
Reinstall Visual studio.
Reinstall .NET Framework (and libraries and so on , the whole bunch)
Reinstall Windows (Which i would prefer not to).

Also, googling the exact error, gives (for me) one exact match in stacktrace , but with no extra info included.

Please, please help me fix this , because i'm almost getting depressed about this thing.
(slightly modified code files can be supplied, but since my colleages can run perfectly, and the code is "confidential" i will not include them right away.)


Thx!
Anton

WPF ListBox with button to delete each element

$
0
0

I'm trying to create a ListBox in WCF that each element in it also has a button to delete it.

From some reason it doesn't work, meaning the button is displayed, but pressing it doesn't trigger the command.

Here is the Xaml code:

<ListBox Name="CustomizedVlanListBox" Background="Transparent" BorderBrush="Transparent" SelectedItem="{Binding SelectedVlanListItem}" ItemsSource="{Binding VLANAdditionalConfigurationSettings}" Height="Auto" Width="auto" >
    <ListBox.ContextMenu>
        <ContextMenu>
            <MenuItem Header="Delete" Command="{Binding RemoveVLANCommand}"/>
        </ContextMenu>
    </ListBox.ContextMenu>
    <ListBox.ItemTemplate>
        <DataTemplate>
            <StackPanel Margin="0,3,3,0" Orientation="Horizontal" >
                <TextBox Foreground="White" IsTabStop="False" Background="Transparent" Width="220" HorizontalAlignment="Left" FontSize="14" VerticalAlignment="Stretch" Text="{Binding Name}" IsReadOnly="True" BorderThickness="0" BorderBrush="Transparent" />
                <TextBox Foreground="Black" Background="White" PreviewTextInput="NumberValidationTextBox" MaxLength="4" Width="150" HorizontalAlignment="Left" VerticalAlignment="Stretch" TextAlignment="Center">
                    <Binding Path="Value" UpdateSourceTrigger="PropertyChanged" >
                        <Binding.ValidationRules>
                            <ExceptionValidationRule />
                        </Binding.ValidationRules>
                    </Binding>
                </TextBox>
                <Button FontSize="14" Width="60" Command="{Binding RemoveVLANCommand}">
                    <Button.Content>
                        <TextBlock>Delete</TextBlock>
                    </Button.Content>
                </Button>
            </StackPanel>
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>


How to Resolve AccessViolationExeception?

$
0
0

Im having a Application,which runs initally fine,but after loading the application multipletimes(say 15 times)it throws the exeception at some point,And i really dont know the Reason why the Exeception is Thrown at this Method alone.

publicclassMyClass2{publicstaticvoidMyMethod(IntPtrPuppy){lock(LockString){MyClass.MyMethod(Puppy);}}}publicclassMyClass{[DllImport("MyDLL.dll")]publicstaticexternvoidMyMethod(IntPtrPuppy);}

If someone Knows why the exeception is thrown and how to resolve it, please let me know...Also FYI im accessing this dll through other different methods which works fine .This alone Shows the Exeception.

Regards,

Vishnuraj Haridoss


Binding value not reflected in the XPS Document

$
0
0

I have changed the template (Button) fill color based on the scale value through binding.This binding value not reflected in the XPS Document. Please find the template and XPS Doocument serialization code as below.

Xaml Code : based on the level value fill color will change.

 <Canvas.Clip>
         <RectangleGeometry Rect="0,2.5,100,100">
                 <RectangleGeometry.Transform>
                        <ScaleTransform ScaleX="1" ScaleY="{Binding Level}" CenterX="0" CenterY="97.5" />
                 </RectangleGeometry.Transform>
          </RectangleGeometry>
</Canvas.Clip>

//XPS Document Code.

                      

//Set up the WPF Control to be Saved
            Canvas controlToPrint= new Canvas();

            //canv is the instance of my canvas containing button.
            controlToPrint = canv;
            canv = null;

            FixedDocument fixedDoc = new FixedDocument();
            PageContent pageContent = new PageContent();
            FixedPage fixedPage = new FixedPage();

            //Create first page of document
            fixedPage.Children.Add(controlToPrint);
            ((System.Windows.Markup.IAddChild)pageContent).AddChild(fixedPage);

            var size = fixedDoc.DocumentPaginator.PageSize;
            pageContent.Measure(size);
            pageContent.Arrange(new Rect(new Point(), size));
            pageContent.UpdateLayout();
            fixedDoc.Pages.Add(pageContent);

            // Configure save file dialog box
            Microsoft.Win32.SaveFileDialog dlg = new Microsoft.Win32.SaveFileDialog();
            dlg.FileName = "MyReport"; // Default file name
            dlg.DefaultExt = ".xps"; // Default file extension
            dlg.Filter = "XPS Documents (.xps)|*.xps"; // Filter files by extension

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

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

                FixedDocument doc = fixedDoc;
                XpsDocument xpsd = new XpsDocument(filename, FileAccess.ReadWrite);
                System.Windows.Xps.XpsDocumentWriter xw = XpsDocument.CreateXpsDocumentWriter(xpsd);
                xw.Write(doc);
                xpsd.Close();
            }

Please suggest me how to achieve this?

Note:

I could able to achieve this while using triggers.But, i should not supposed to use triggers.


Thanks,

Ranjitha.


Error when Add GMap Control to the Toolbox in WPF Project

$
0
0

I'm Trying to Add GMap Control in my WPF project. But Got Error Message ("There is no component in GMap.NET.WindowsPresentation.dll that can be placed on the toolbox").

Also I am trying to add namespace in Xaml file with getting Error "Unable to load DLL 'SQLite.Interop.dll'. this specified module could not found. (Exception from HRESULT: 0x8007007E)" 

How can I scroll the scrollviewer whenever a listbox inside it?

$
0
0

Here is my code:

<Window x:Class="WpfApp1.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:WpfApp1"
        mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="800" Loaded="Window_Loaded">
    <Grid>
        <ScrollViewer  Height="300" VerticalAlignment="Top">
            <StackPanel>
                <Grid>
                    <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>
                    </Grid.RowDefinitions>
                    <TextBlock>123123</TextBlock>
                    <TextBlock Grid.Row="1">123123</TextBlock>
                    <TextBlock Grid.Row="2">123123</TextBlock>
                    <TextBlock Grid.Row="3">123123</TextBlock>
                    <TextBlock Grid.Row="4">123123</TextBlock>
                    <TextBlock Grid.Row="5">123123</TextBlock>
                    <TextBlock Grid.Row="6">123123</TextBlock>
                </Grid>
                <ListBox ScrollViewer.CanContentScroll="False" ScrollViewer.HorizontalScrollBarVisibility="Disabled" ScrollViewer.VerticalScrollBarVisibility="Disabled" ItemsSource="{Binding OC}">
                    <ListBox.ItemTemplate>
                        <DataTemplate>
                            <Grid>
                                <Grid.RowDefinitions>
                                    <RowDefinition></RowDefinition>
                                    <RowDefinition></RowDefinition>
                                </Grid.RowDefinitions>
                                <TextBlock Text="{Binding abc}"></TextBlock>
                                <TextBlock Text="{Binding cde}"></TextBlock>
                            </Grid>
                        </DataTemplate>
                    </ListBox.ItemTemplate>
                </ListBox>
            </StackPanel>
        </ScrollViewer>
    </Grid>
</Window>

Whenever the mouse over the ListBox, the ScrollViewer can not scroll any more.

I know maybe the ListBox scrollable affect this. Meanwhile, after I set the CanContentScroll to false and disabled the ScrollBarVisibility, it still like this.

I don't need the ListBox scrollable but display all inside it. I just need all can only scrollable by the ScrollViewer.

I have not any Control to replace the ListBox for I need to binding to a ViewModel.

How can I solve this? Please help me.

KeyDown EventHandler ignored when pressing 'Enter'

$
0
0
I am trying to display a MessageBox when the user presses enter on the keyboard, but the event does not seem to fire for the Enter-key? It works with other keys but not with enter...how to solve?
private void richTextBox1_KeyDown(object sender, KeyEventArgs e)
{
    if (e.Key == Key.Return)
     MessageBox.Show("");
}
<RichTextBox Name="richTextBox1" KeyDown="richTextBox1_KeyDown"....>
Viewing all 18858 articles
Browse latest View live


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