I want to pass the webview2 control on the page to the ViewModel after clicking the button.
The following is part of the code for xaml:
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="auto" />
<RowDefinition Height="auto"/>
<RowDefinition />
</Grid.RowDefinitions>
<StackPanel>
<!--Click the button "Button_single", and the value of parameter can be obtained from ViewModel as Microsoft.Web.WebView2.Wpf.WebView2 type-->
<Button Command="{Binding BtnCommand1}" CommandParameter="{Binding ElementName=webView_single}">Button_single</Button>
<!--Click the button "Button_list", and the value of parameter obtained from ViewModel is null. Why?-->
<Button Command="{Binding BtnCommand1}" CommandParameter="{Binding ElementName=webView_list}">Button_list</Button>
<webview2:WebView2 Name="webView_single" Source="https://www.google.com/" Grid.Row="1">
<behaviour:Interaction.Triggers>
<behaviour:EventTrigger EventName="NavigationCompleted">
<behaviour:CallMethodAction TargetObject="{Binding}" MethodName="webView2_NavigationCompleted" />
</behaviour:EventTrigger>
</behaviour:Interaction.Triggers>
</webview2:WebView2>
</StackPanel>
<ScrollViewer Grid.Row="2" >
<ItemsControl Grid.Row="1" ItemsSource="{Binding AccountDtos}" HorizontalAlignment="Center">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<WrapPanel />
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<ItemsControl.ItemTemplate>
<DataTemplate>
<md:TransitioningContent OpeningEffect="{md:TransitionEffect Kind=ExpandIn}" >
<Grid Width="600" MinHeight="800" MaxHeight="250" Margin="8" >
<Grid.RowDefinitions>
<RowDefinition Height="auto" />
<RowDefinition />
</Grid.RowDefinitions>
<Border CornerRadius="4" Grid.RowSpan="5" Background="#7F7F7F" />
<StackPanel Orientation="Horizontal">
<TextBlock Text="UserName:" />
<TextBlock Padding="5,0" Text="{Binding UserName}" />
<TextBlock Text="Password:" />
<TextBlock Padding="5,0" Text="{Binding Password}" />
</StackPanel>
<webview2:WebView2 Name="webView_list" Source="https://www.google.com/" Grid.Row="1">
<behaviour:Interaction.Triggers>
<behaviour:EventTrigger EventName="NavigationCompleted">
<behaviour:CallMethodAction TargetObject="{Binding}" MethodName="webView2_NavigationCompleted" />
</behaviour:EventTrigger>
</behaviour:Interaction.Triggers>
</webview2:WebView2>
</Grid>
</md:TransitioningContent>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</ScrollViewer>
</Grid>
I want to pass the webview2 control on the page to the ViewModel after clicking the button.
The following is part of the code for xaml:
public DelegateCommand<object> BtnCommand1 { get => new DelegateCommand<object>(Execute1); }
private void Execute1(object parameter)
{
//In the xaml page, if you click the button "Button_single", you can get the parameter value of Microsoft.Web.WebView2.Wpf.WebView2 type
//If you click the button "Button_list", the value of parameter is null. Why and how can it not be null?
Console.Write(parameter);
}
I want to get the webView control in the list control in the ViewModel. How should I write this code?
(This question Passing a Different button in Command Parameter Wpf Similar to my question, but different)
There are two reasons the webView_list commandparameter cannot work.
The first is conceptual. There are going to be a list of those WebView2s rather than just one. How's it supposed to know which one it is to reference?
You know if you have a list of anything in c# then you'd have to reference by index or something which one in the list you want.
The same would be true for xaml. You'd need to tell it to go look at row 0 or 1 or 2 or whatever.
There is another complication though. WPF has the concept of namescopes. All the controls directly in the grid of your window are in the same namescope.
When you have templates and in particular lists of things that becomes a bit more complicated.
Let's think about this from the bottom up though.
You've named a control webView_list. This is in an itemtemplate. So when you have 4 items you will have 4 WebView2s. But it will not error. Somehow those 4 named controls do not collide with one another.
This is because each of those items produced from that itemtemplate have their own namescope. The first item has a namescope of it's own, the second has it's own namescope etc.
You cannot just use elementname to reference something in a different namescope. So you can't get at a specific webview2 in that list using elementname from outside the item it's in.
In any case, you need some way to tell which item.
You could use selecteditem if this was a listbox.
An itemscontrol has no selection though. To get at your webview2 in an item the usual thing to do would be to put the button in the itemtemplate and the same namescope. That could then use relativesource to get to the command in the parent datacontext. Something like:
<ItemsControl.ItemTemplate>
<DataTemplate>
<md:TransitioningContent OpeningEffect="{md:TransitionEffect Kind=ExpandIn}" >
<Grid Width="600" MinHeight="800" MaxHeight="250" Margin="8" >
<Grid.RowDefinitions>
<RowDefinition Height="auto" />
<RowDefinition Height="auto" />
<RowDefinition />
</Grid.RowDefinitions>
<Border CornerRadius="4" Grid.RowSpan="5" Background="#7F7F7F" />
<StackPanel Orientation="Horizontal">
<TextBlock Text="UserName:" />
<TextBlock Padding="5,0" Text="{Binding UserName}" />
<TextBlock Text="Password:" />
<TextBlock Padding="5,0" Text="{Binding Password}" />
</StackPanel>
<Button Command="{Binding DataContext.BtnCommand1, RelativeSource={RelativeSource AncestorType ItemsControl}}"
CommandParameter="{Binding ElementName=webView_list}" Grid.Row="2">Button_list</Button>
<webview2:WebView2 Name="webView_list" Source="https://www.google.com/" Grid.Row="2">
<behaviour:Interaction.Triggers>
<behaviour:EventTrigger EventName="NavigationCompleted">
<behaviour:CallMethodAction TargetObject="{Binding}" MethodName="webView2_NavigationCompleted" />
</behaviour:EventTrigger>
</behaviour:Interaction.Triggers>
</webview2:WebView2>
</Grid>
</md:TransitioningContent>
</DataTemplate>
</ItemsControl.ItemTemplate>
Related
I am developing a UWP application and in one scenario I have to add Drag and drop feature on a ListView . But DragItemsStarting event doesn't get trigger when ItemsTemplate is defined.
In one scenario when I do Drag operation on ListViewItem by selecting its border it works well but when I do the drag on item it doesn't work.
Here is the Image for drag operation on items border:
Here is the XAML code:
<ListView Grid.Row="3"
ScrollViewer.IsScrollInertiaEnabled="True"
ScrollViewer.VerticalScrollBarVisibility="Auto"
ScrollViewer.VerticalScrollMode="Enabled"
CanDragItems="True"
CanReorderItems="True"
ReorderMode="Enabled"
AllowDrop="True"
SelectionMode="Single"
VerticalAlignment="Stretch"
HorizontalAlignment="Stretch"
DragItemsStarting="{x:Bind VM.DragItemsStarting, Mode=OneWay}"
DragOver="{x:Bind VM.DragOver, Mode=OneWay}"
Drop="{x:Bind VM.DragDrop, Mode=OneWay}"
ItemsSource="{x:Bind ItemSource, Mode=OneWay}">
<ListView.ItemTemplate>
<DataTemplate x:DataType="model:Model">
<Button HorizontalAlignment="Stretch"
HorizontalContentAlignment="Stretch"
Command="{Binding DataContext.PageCommand, ElementName=pageMain}">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="*" />
<RowDefinition Height="10" />
</Grid.RowDefinitions>
<TextBlock Text="{x:Bind ShowName,Mode=OneWay}"
VerticalAlignment="Center"
HorizontalAlignment="Center"
Foreground="Black"
TextWrapping="WrapWholeWords"
Margin="3" />
<ProgressBar Grid.Row="1"
Margin="0"
Value="25"
Height="8"
VerticalAlignment="Bottom"
Foreground="Green" />
</Grid>
</Button>
</DataTemplate>
</ListView.ItemTemplate>
Is there any way I can perform drag operation on complete ListViewItem ?
You should avoid the use of Button directly inside ItemTemplate if you are having drag and drop features in your application, use a Grid or something else.
Now to enable click feature on ListItem set IsItemClickEnabled property to True and use ItemClick event on the ListView.
I'm using hardcodet's WPF NotifyIcon in my app, which is being implemented using MVVM Light. I'm trying to create a custom TrayPopup for the icon. In this popup I have an ItemsControl, whose ItemsSource is a list of objects "NumberList" in my ViewModel. For my DataTemplate I'm using a grid which display an property called "Id" of my source object, and a button. The button I'm trying to tie back to a RelayCommand in my ViewModel. I've done similar things with ItemsControls in the past by Binding using a RelativeSource to get the DataContext of the Window Ancestor. I tried a similar approach this time, but when I run the app, open the TrayPopup, and click the button nothing happens. My command is not fired in my ViewModel.
As a test I tried adding another button to my TrayPopup and binding its command to the same one in my ViewModel. That binding works fine, so it's not the command as far as I can tell.
Like I said, I've used this technique almost exactly in the past, just never before in a NotifyIcon. I've tried specifying the ElementName in the button Binding to the name of my Window, which didn't work. I've also tried changing the RelativeSource to the parent TaskbarIcon, also without success.
Here is an example implementation of what the NotifyIcon with the same problem:
<tb:TaskbarIcon PopupActivation="LeftOrRightClick">
<tb:TaskbarIcon.TrayPopup>
<Grid Background="White">
<Grid.RowDefinitions>
<RowDefinition Height="200"/>
<RowDefinition Height="30"/>
</Grid.RowDefinitions>
<ScrollViewer Grid.Row="0">
<ItemsControl ItemsSource="{Binding NumberList, Mode=OneWay, UpdateSourceTrigger=PropertyChanged}">
<ItemsControl.ItemTemplate>
<DataTemplate>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="200"/>
<ColumnDefinition/>
</Grid.ColumnDefinitions>
<Label Grid.Column="0" Content="{Binding Id, Mode=OneWay, UpdateSourceTrigger=PropertyChanged}"/>
<Button Grid.Column="1" Content="Test" Command="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Window}}, Path=DataContext.TestCommand}"/> <!--This binding doesn't work!-->
</Grid>
</DataTemplate>
</ItemsControl.ItemTemplate>
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<StackPanel/>
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
</ItemsControl>
</ScrollViewer>
<Button Grid.Row="1" Content="Test2" Command="{Binding TestCommand}"/> <!--This works-->
</Grid>
</tb:TaskbarIcon.TrayPopup>
</tb:TaskbarIcon>
I'm fairly confident everything in the ViewModel is correct as I have been using a previous version of this app that I wrote a while ago. So far I haven't run in to any problems other than this NotifyIcon. Any ideas?
After banging away at it for a while I found an answer to my problem. The StackPanel in my ItemsPanelTemplate had the DataContext which contained the command I wanted to bind my button to, my main ViewModel. By specifying a name for the StackPanel, I was able to set the ElementName of my button to its name, and then the binding worked. Not sure why this method worked with the StackPanel and not the main Window though.
Anyway, here's the updated code if anyone runs in to this same problem:
<tb:TaskbarIcon PopupActivation="LeftOrRightClick">
<tb:TaskbarIcon.TrayPopup>
<Grid Background="White">
<Grid.RowDefinitions>
<RowDefinition Height="200"/>
<RowDefinition Height="30"/>
</Grid.RowDefinitions>
<ScrollViewer Grid.Row="0">
<ItemsControl ItemsSource="{Binding NumberList, Mode=OneWay, UpdateSourceTrigger=PropertyChanged}">
<ItemsControl.ItemTemplate>
<DataTemplate>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="200"/>
<ColumnDefinition/>
</Grid.ColumnDefinitions>
<Label Grid.Column="0" Content="{Binding Id, Mode=OneWay, UpdateSourceTrigger=PropertyChanged}"/>
<Button Grid.Column="1" Content="Test" Command="{Binding ElementName=trayMainStack, Path=DataContext.TestCommand}"/> <!--Updated binding works!-->
</Grid>
</DataTemplate>
</ItemsControl.ItemTemplate>
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<StackPanel Name="trayMainStack"/>
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
</ItemsControl>
</ScrollViewer>
<Button Grid.Row="1" Content="Test2" Command="{Binding TestCommand}"/> <!--This works-->
</Grid>
</tb:TaskbarIcon.TrayPopup>
</tb:TaskbarIcon>
I've a problem to connect.
I started to connect my tabs with a tabcontrol.ressources and it worked to show the text of each tabs.
Then I wanted to had a scroll for my TabItems and it doesn't work, nothing shows in tab... I can't even use tabcontrol.ressources anymore...
<DockPanel>
<Button Background="DarkGoldenrod" Height="Auto" Command="{Binding OpenFlyoutDataCommand}">
<StackPanel>
<materialDesign:PackIcon Kind="ArrowRightBoldCircleOutline" Width="30" Height="30"/>
</StackPanel>
</Button>
<TabControl ItemsSource="{Binding TabEDCWaferData, Mode=TwoWay}"
SelectedItem="{Binding SelectedTabEDCWaferData}">
<!-- Used to create a scroolbar for tabitems -->
<TabControl.Template>
<ControlTemplate TargetType="TabControl">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition />
</Grid.RowDefinitions>
<ScrollViewer HorizontalScrollBarVisibility="Auto" VerticalScrollBarVisibility="Hidden" >
<TabPanel Grid.Column="0" Grid.Row="0"
Margin="2,2,2,0" IsItemsHost="true"/>
</ScrollViewer>
<ContentPresenter ContentSource="..."/>
</Grid>
</ControlTemplate>
</TabControl.Template>
<!-- Contains the text in the tab item ! -->
<TabControl.Resources>
<DataTemplate DataType="TabItem">
<DockPanel>
<TextBlock Text="{Binding RelativeSource={RelativeSource AncestorType={x:Type TabItem}}, Path=Content}" />
</DockPanel>
</DataTemplate>
</TabControl.Resources>
</TabControl>
</DockPanel>
This is connected to a collection of TabItem, where I've a function to add Items binding to an other button.
private ObservableCollection<TabItem> _TabEDCWaferData;
public ObservableCollection<TabItem> TabEDCWaferData
{
get { return _TabEDCWaferData; }
set
{
_TabEDCWaferData = value;
RaisePropertyChanged("TabEDCWaferData");
}
}
public void AddTabItem(string name)
{
TabItem tab = new TabItem();
tab.Header = name;
tab.Content = "Temporary content";
TabEDCWaferData.Add(tab);
}
I read that I have to use the ContentPresenter, but I don't know how to bind it. I think this is not working with TabItems...
I just want to bind it as I did in the Ressources by using the ContentPresenter.
I hope that I'm clear enough ! Thanks
EDIT : I try to display in the ContentPresenter the selected item tab content that I add in the function `AddTabItem.
With ContentPresenter, most times, this does the job:
<ContentPresenter />
The default ContentSource is "Content". That means it'll look at the Content property of the templated parent and it'll take whatever it finds there for its own content.
But that doesn't help you at all, and you don't have to use ContentPresenter; it's just a convenience. In this case, the content you want to present is SelectedItem.Content, which isn't a valid ContentSource for ContentPresenter. But you can do the same thing with a binding on a ContentControl instead:
<TabControl.Template>
<ControlTemplate TargetType="TabControl">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition />
</Grid.RowDefinitions>
<ScrollViewer
Grid.Row="0"
HorizontalScrollBarVisibility="Auto"
VerticalScrollBarVisibility="Hidden"
>
<TabPanel
Grid.Column="0"
Margin="2,2,2,0" IsItemsHost="true"/>
</ScrollViewer>
<ContentControl
Grid.Row="1"
Content="{Binding SelectedItem.Content, RelativeSource={RelativeSource TemplatedParent}}"
/>
</Grid>
</ControlTemplate>
</TabControl.Template>
TemplateBinding isn't going to work with a Path such as "SelectedItem.Content"; it only accepts names of properties on the templated parent. I fixed your Grid.Row attributes, too.
Also, you may as well delete that DataTemplate for TabItem that you put in TabControl.Resources. That's not what DataTemplate is for; you use DataTemplates to define visual presentations for your viewmodel classes, but TabItem is a control. It already knows how to display itself, and in fact that DataTemplate is being ignored, so it's best not to leave it there; you'll only waste time later on making changes to it and trying to figure out why it's not having any effect. Your TabItems will display correctly without it.
Try something like this ?
<ContentPresenter Content="{TemplateBinding Content}" />
Edit
<ContentPresenter x:Name="PART_SelectedContentHost" ContentSource="SelectedContent" />
I am using a DataTemplateSelector to select different UserControls (reference http://tech.pro/tutorial/807/wpf-tutorial-how-to-use-a-datatemplateselector), according the selected path I select the needed UserControl.
The problem is now, when using the WebBrowser Control, I should bind it to ActualHight of MyScrollViewer, but on all others it works with Hight or else the scroll bar is displayed bad. Must come from the WebBrowser control.
How can I switch the Bindings in the ContentControl between Hight/ActualHight depending of the loaded UserControl?
<DataTemplate x:Key="WebTemplate1">
<DockPanel LastChildFill="True">
<controls:WebBrowserUserControl SourceHtml="{Binding Converter={StaticResource UriConverter1}}" />
</DockPanel>
</DataTemplate>
<DataTemplate x:Key="ImgTemplate1">
<Image Source="{Binding Converter={StaticResource RelativeToAbsolutePathConverter1}}"
Stretch="None" />
</DataTemplate>
...
<ScrollViewer Name="MyScrollViewer"
HorizontalAlignment="Stretch"
VerticalAlignment="Stretch"
DockPanel.Dock="Left"
HorizontalScrollBarVisibility="Auto"
VerticalScrollBarVisibility="Auto">
<Grid x:Name="MyGridHelper">
<Grid.RowDefinitions>
<RowDefinition Height="*" />
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<DockPanel x:Name="MyDockPanel" Dock="Top" HorizontalAlignment="Left">
<ContentControl x:Name="MyContentControl"
Width="{Binding ElementName=MyScrollViewer,
Path=Width/ActualWidth}"
Height="{Binding ElementName=MyScrollViewer,
Path=Height/ActualHight}"
Content="{Binding Path=CurrentItem1,
Mode=OneWay}"
ContentTemplateSelector="{StaticResource MyTemplateSelector}" />
</DockPanel>
</Grid>
</ScrollViewer>
The DataTemplateSelector by itself cannot affect the other properties of the ContentControl, however, you could use a Converter to determine the Width\Height based on the same logic used to determine which template to use. So something like this:
<ContentControl x:Name="MyContentControl"
Width="{Binding ElementName=MyScrollViewer, Converter={StaticResource MyWidthConverter}, ConverterParameter="???"}"
Height="{Binding ElementName=MyScrollViewer, Converter={StaticResource MyHeightConverter}, ConverterParameter="???"}"
Content="{Binding Path=CurrentItem1, Mode=OneWay}"
ContentTemplateSelector="{StaticResource MyTemplateSelector}" />
I put question marks for the ConverterParameter because I'm not clear on how you determine which case calls for which Width/Height. But you can pass in a parameter that will allow you to decide which value to pass back, and based on that decision, the Converter can determine whether to get the ActualWidth/ActualHeight or the Width/Height of the ScrollViewer that is passed in.
This is a problem I've been trying to solve for a couple of days but I'm yet to find a good solution.
I have a main WPF window which contains a StackPanel. I also have a class called "MessageManagement" which contains a List of custom WPF controls called "MessagePreview".
MessagePreview
<UserControl x:Class="FinalYearProject.MessagePreview"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
mc:Ignorable="d"
d:DesignHeight="58" d:DesignWidth="254" Background="White" BorderThickness="1" BorderBrush="#FF320000">
<Grid Name="grid1">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="50" MaxWidth="50" MinWidth="50" />
<ColumnDefinition Width="197*" MinWidth="20" />
</Grid.ColumnDefinitions>
<Grid Grid.Column="1" Name="grid2">
<Grid.RowDefinitions>
<RowDefinition Height="31*" />
<RowDefinition Height="34*" />
<RowDefinition Height="33*" />
</Grid.RowDefinitions>
<Label Content="-ERROR-" Height="28" HorizontalAlignment="Left" Margin="2,1,0,0" Name="senderLabel" VerticalAlignment="Top" Foreground="#FF0000B4" Grid.RowSpan="2" />
<Label Content="-ERROR-" Height="33" HorizontalAlignment="Left" Name="previewLabel" VerticalAlignment="Top" Margin="-1,17,0,0" Grid.RowSpan="3" />
<Label Content="-Error-" Grid.Row="1" Height="28" HorizontalAlignment="Left" Margin="0,16,6,0" Name="timeLabel" VerticalAlignment="Top" Grid.RowSpan="2" Width="196" />
</Grid>
<Grid Name="grid3">
<Grid.RowDefinitions>
<RowDefinition Height="29*" />
<RowDefinition Height="27*" />
</Grid.RowDefinitions>
<Image Height="38" HorizontalAlignment="Center" Margin="3,0,6,20" Name="image1" Stretch="Fill" VerticalAlignment="Bottom" Width="41" Source="/FinalYearProject;component/Images/twitter-bird-light-bgs.png" Grid.RowSpan="2" />
<CheckBox Height="16" Margin="15,0,22,6" Name="checkBox" VerticalAlignment="Bottom" Grid.Row="1" IsChecked="False" />
</Grid>
</Grid>
MessageManagement
List<MessagePreview> unread = new List<MessagePreview>();
public bool messagesLocked()
{
foreach (MessagePreview m in unread)
{
if ((bool)m.checkBox.IsChecked)
return true;
}
return false;
}
MainWindow C#
MessageManagement messageManagement;
MessagesPanel1 is a blank StackPanel inside MainWindow
if (!messageManagement.messagesLocked())
{
foreach (Message m in messageManagement.getListOfMessages()
{
MessagesPanel1.Children.Add(m)
}
}
When you add the custom control to the StackPanel it creates a duplicate of the original, which means changing a value on the controls in the StackPanel does not affect the controls in my MessageManagement List.
Is there a way that I can reference my original controls so that they change together? I looked into DataBinding but I'm not sure if that's the right area.
Again, You do not make a List of UI elements in WPF. You use an ItemsControl and set its ItemTemplate Property to whatever UI you need to represent your items:
<ItemsControl ItemsSource="{Binding Messages}">
<ItemsControl.ItemTemplate>
<DataTemplate>
<!-- Everything you placed in your usercontrol, or else an instance of your usercontrol itself -->
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
If saying "change" you mead a data, inside WPF you never and ever need to access UI elements directly, as they are subject to change. What you have to do is to read the data bound to them. With correct databinding setupped on that controls you will have always updated information.
Accessing UI elements is never easy, but except that, it's completely unreliable way to access your data, as the way control is injected into the VisualTree may be changed, so your code will fail on next update.
For example on how to architect that can have a look here:
WPF Data Binding Examples