I'm trying to create a canvas that takes items from ListView and puts them where the user wants.
Canvas won't fire my DragEnter and Drop events. Here is my code for ListView and Canvas properties.
private void itemList_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
startPoint = e.GetPosition(null);
isDragging = true;
}
private void itemList_MouseMove(object sender, MouseEventArgs e)
{
Point mousePos = e.GetPosition(null);
Vector diff = startPoint - mousePos;
if (e.LeftButton == MouseButtonState.Pressed &&
(Math.Abs(diff.X) > SystemParameters.MinimumHorizontalDragDistance ||
Math.Abs(diff.Y) > SystemParameters.MinimumVerticalDragDistance))
{
ListView listView = sender as ListView;
ListViewItem listViewItem =
FindAncestor<ListViewItem>((DependencyObject)e.OriginalSource);
Model.Resource student = (Model.Resource)listView.ItemContainerGenerator.
ItemFromContainer(listViewItem);
dragItem = new DDitem(student.getName(), student.getIco());
DataObject dragData = new DataObject("myFormat", dragItem);
DragDrop.DoDragDrop(listViewItem, dragData, DragDropEffects.Move);
}
}
Now for my <Canvas>
private static T FindAncestor<T>(DependencyObject current) where T : DependencyObject
{
do
{
if (current is T)
{
return (T)current;
}
current = VisualTreeHelper.GetParent(current);
}
while (current != null);
return null;
}
private void can_DragEnter(object sender, DragEventArgs e)
{
if (!e.Data.GetDataPresent("myFormat") || sender == e.Source)
{
e.Effects = DragDropEffects.None;
}
Console.WriteLine("Pokusava drag enter");
}
private void can_Drop(object sender, DragEventArgs e)
{
Console.WriteLine("Pokusava drop");
if (e.Data.GetDataPresent("myFormat"))
{
Model.Resource student = e.Data.GetData("myFormat") as Model.Resource;
resources.Remove(student);
isDragging = false;
}
}
My XAML code for Canvas and ListView is below
<Canvas Name="can" Background="Transparent" Margin="10,10,10,0" Grid.Row="1" AllowDrop="True" DragEnter="can_DragEnter" Drop="can_Drop" />
<ListView x:Name="itemList" Grid.Column="1" HorizontalAlignment="Stretch" Margin="7,23,6,0" Grid.Row="1" VerticalAlignment="Stretch" Background="#324251" ItemsSource="{Binding Path=resources}" FontSize="16" Foreground="Wheat" PreviewMouseLeftButtonDown="itemList_PreviewMouseLeftButtonDown" MouseMove="itemList_MouseMove" >
<ListView.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<Image Source="{Binding ico}" Width="70" Height="70"></Image>
<TextBlock Text="{Binding name}" HorizontalAlignment="Center" VerticalAlignment="Center"></TextBlock>
</StackPanel>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
Output gives no exceptions or errors.
Problem fixed, the problem was that I've put Canvas before Image
Now, I've ran to another problem, I'm trying to add my UserControl called DDItem to canvas, but with no luck. It should follow my mouse pointer and when I release my mouse, it should be put on the canvas. It does get added to my list of dragged items but I cant see it.
XAML code of my DDItem is below
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="61*"/>
<RowDefinition Height="14*"/>
</Grid.RowDefinitions>
<Image x:Name="mask" Source="{Binding Path=src}" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" Stretch="Fill" Grid.Row="0"/>
<Label x:Name="label" Content="{Binding Path=name}" HorizontalContentAlignment="Center" VerticalContentAlignment="Center" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" Grid.Row="1" Foreground="Wheat" FontSize="40"/>
</Grid>
Code inside my DDItem class
public partial class DDitem : UserControl
{
private string _name;
private string _path;
private Point position;
public string name
{
get;
set;
}
public string path
{
get;
set;
}
public DDitem(string name, string path)
{
this.name = name;
this.path = path;
this.Width = 100;
this.Height = 100;
this.DataContext=this;
InitializeComponent();
}
public Point getPosition()
{
return position;
}
public void setPosition(Point pos)
{
position = pos;
}
}
Now for my Canvas events:
private void can_DragEnter(object sender, DragEventArgs e)
{
if (!e.Data.GetDataPresent("myFormat") || sender == e.Source)
{
e.Effects = DragDropEffects.None;
}
}
private void can_Drop(object sender, DragEventArgs e)
{
if (e.Data.GetDataPresent("myFormat"))
{
can.Children.Add(dragItem);
dragItem.Visibility = Visibility.Visible;
Canvas.SetTop(dragItem, dragItem.getPosition().Y);
Canvas.SetLeft(dragItem, dragItem.getPosition().X);
isDragging = false;
resOnCanvas.Add(dragItem);
}
}
private void can_DragOver(object sender, DragEventArgs e)
{
if (dragItem != null)
{
if (!dragItem.IsVisible)
{
dragItem.Visibility = Visibility.Visible;
}
dragItem.setPosition(e.GetPosition(can));
Console.WriteLine(dragItem.getPosition().X + " " + dragItem.getPosition().Y);
}
}
Related
I'm trying to bind color of Gauge fill property to SolidColorBrush i created code behind. It works fine for progressbar but not for Gauge. The binding works but it doesn't update automatically as same as progressbar. Is that possible to update it while not having to re-plot this? Thank you
XAML:
<Grid Grid.Column="0">
<lvc:Gauge Grid.Row="2" Grid.Column="0" Margin="5"
From="0" To="{Binding Path=attaBitrateUP}" Value="{Binding Path=actBitrateUP}" GaugeActiveFill="{Binding Path=up, UpdateSourceTrigger=PropertyChanged}"/>
</Grid>
<Grid Grid.Row="2">
<StackPanel>
<TextBlock Text="Carrier count:" Height="20" VerticalAlignment="Bottom" Margin="10,0,0,5"/>
<ProgressBar Height="25" Margin="10,0,10,0" Value="{Binding Path=chartValuesUP}" Maximum="{Binding Path=chartValuesCount}" Foreground="{Binding Path=up}" Background="{Binding Path=down}"/>
</StackPanel>
</Grid>
Code Behind:
private SolidColorBrush _up = new SolidColorBrush(Colors.OrangeRed);
public SolidColorBrush up
{
get { return _up; }
set
{
_up = value;
NotifyPropertyChanged();
}
}
public event PropertyChangedEventHandler PropertyChanged;
private void NotifyPropertyChanged([CallerMemberName] String propertyName = "")
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
The property GaugeActiveFill has no property changed callback registered. Therefore, it won't detect the change when the data binding is invoked. The library is implemented quite sloppy, frankly said.
But we can fix it ourselves by extending the original Gauge class to register the missing property changed handler:
FixedGauge.cs
public class FixedGauge : Gauge
{
static FixedGauge()
{
GaugeActiveFillProperty.OverrideMetadata(typeof(FixedGauge), new FrameworkPropertyMetadata(default(Brush), OnGaugeActiveFillChanged));
}
private PieSlice PART_Pie { get; set; }
public FixedGauge()
{
this.Loaded += OnLoaded;
}
private void OnLoaded(object sender, RoutedEventArgs e)
{
if (TryFindVisualChildElementByName(this, null, out PieSlice pie))
{
this.PART_Pie = pie;
}
}
private static void OnGaugeActiveFillChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
=> (d as FixedGauge).OnGaugeActiveFillChanged(e.OldValue as Brush, e.NewValue as Brush);
protected virtual void OnGaugeActiveFillChanged(Brush oldBrush, Brush newBrush)
{
if (this.PART_Pie == null)
{
return;
}
this.PART_Pie.Fill = newBrush;
}
public static bool TryFindVisualChildElementByName<TChild>(
DependencyObject parent,
string childElementName,
out TChild resultElement) where TChild : FrameworkElement
{
resultElement = null;
if (parent is Popup popup)
{
parent = popup.Child;
if (parent == null)
{
return false;
}
}
for (var childIndex = 0; childIndex < VisualTreeHelper.GetChildrenCount(parent); childIndex++)
{
DependencyObject childElement = VisualTreeHelper.GetChild(parent, childIndex);
if (childElement is TChild frameworkElement)
{
if (string.IsNullOrWhiteSpace(childElementName) || frameworkElement.Name.Equals(
childElementName,
StringComparison.OrdinalIgnoreCase))
{
resultElement = frameworkElement;
return true;
}
}
if (TryFindVisualChildElementByName(childElement, childElementName, out resultElement))
{
return true;
}
}
return false;
}
}
Then use this new control in place of the original:
<local:FixedGauge Grid.Row="2" Grid.Column="0" Margin="5"
From="0" To="{Binding Path=attaBitrateUP}"
Value="{Binding Path=actBitrateUP}"
GaugeActiveFill="{Binding Path=up}" />
I'm new to UWP canvas element. From the moment I have been finding the way to implement it. I have found this link this link which implementing the control that I want. However I follow the class that define in it. I can't inherit the Thumb control which showing it is Sealed type. Is there anyone know how to find a way out to implement this?
public class MoveThumb : Thumb
{
public MoveThumb(Control dataContext, DragDeltaEventHandler dragDelta)
{
DataContext = dataContext;
DragDelta = dragDelta;
}
public Control DataContext { get; private set; }
public DragDeltaEventHandler DragDelta { get; }
private void MoveThumb_DragDelta(object sender, DragDeltaEventArgs e)
{
Control designerItem = this.DataContext as Control;
if (designerItem != null)
{
double left = Canvas.GetLeft(designerItem);
double top = Canvas.GetTop(designerItem);
Canvas.SetLeft(designerItem, left + e.HorizontalChange);
Canvas.SetTop(designerItem, top + e.VerticalChange);
}
}
}
I've got some sample. Think you'll get the idea. Here's UserControl XAML:
Width="256"
Height="128">
<Grid x:Name="ContainerGrid" Background="Transparent"
ManipulationMode="TranslateX,TranslateY"
ManipulationStarted="Manipulator_OnManipulationStarted"
ManipulationDelta="Manipulator_OnManipulationDelta">
<Viewbox IsHitTestVisible="False">
<TextBlock Text="Text" Foreground="Lime"/>
</Viewbox>
<Rectangle x:Name="ResizeRectangle" IsHitTestVisible="False"
Width="16" Height="16" Fill="Orange"
VerticalAlignment="Bottom" HorizontalAlignment="Right"/>
<Rectangle Stretch="Fill" Stroke="DeepPink" StrokeThickness="2"
IsHitTestVisible="False"/>
</Grid>
And a code behind:
private bool _isResizing;
public Manipulator()
{
InitializeComponent();
}
private void Manipulator_OnManipulationStarted(object sender, ManipulationStartedRoutedEventArgs e)
{
if (e.Position.X > Width - ResizeRectangle.Width && e.Position.Y > Height - ResizeRectangle.Height) _isResizing = true;
else _isResizing = false;
}
private void Manipulator_OnManipulationDelta(object sender, ManipulationDeltaRoutedEventArgs e)
{
if (_isResizing)
{
Width += e.Delta.Translation.X;
Height += e.Delta.Translation.Y;
}
else
{
Canvas.SetLeft(this, Canvas.GetLeft(this) + e.Delta.Translation.X);
Canvas.SetTop(this, Canvas.GetTop(this) + e.Delta.Translation.Y);
}
}
After creating this UserControl just place it into your Canvas:
<Canvas>
<local:Manipulator/>
</Canvas>
I called it Manipuilator.
And here's how it looks like:
I have two InkCanvases stacked and I'd like to get the top to pass inking to the bottom. I set the top to ishittestvisible=false but it still receives the inking. Then as a test I set both to false and the top still gets inking...what am I missing?
I created a blank project and it exhibits the same problem. Here's the code:
MainPage.xaml
<RelativePanel>
<StackPanel Name="stackPanelButtons" Orientation="Vertical">
<Button Name="buttonTop" Content="T" Height="50" Click="buttonTop_Click"/>
<Button Name="buttonBottom" Content="B" Height="50" Click="buttonBottom_Click"/>
<Button Name="buttonTopHit" Content="TH" Height="50" Click="buttonTopHit_Click"/>
<Button Name="buttonBottomHit" Content="BH" Height="50" Click="buttonBottomHit_Click"/>
</StackPanel>
<InkCanvas Name="inkCanvasBottom" RelativePanel.RightOf="stackPanelButtons" Width="500" Height="500"/>
<InkCanvas Name="inkCanvasTop" RelativePanel.RightOf="stackPanelButtons" Width="500" Height="500" Loaded="inkCanvasTop_Loaded"/>
</RelativePanel>
MainPage.cs
public sealed partial class MainPage : Page
{
public MainPage()
{
this.InitializeComponent();
}
private void buttonTop_Click(object sender, RoutedEventArgs e)
{
if(buttonTop.Content.Equals("T"))
{
inkCanvasTop.Visibility = Visibility.Collapsed;
buttonTop.Content = "t";
}
else
{
inkCanvasTop.Visibility = Visibility.Visible;
buttonTop.Content = "T";
}
}
private void buttonBottom_Click(object sender, RoutedEventArgs e)
{
if (buttonBottom.Content.Equals("B"))
{
inkCanvasBottom.Visibility = Visibility.Collapsed;
buttonBottom.Content = "b";
}
else
{
inkCanvasBottom.Visibility = Visibility.Visible;
buttonBottom.Content = "B";
}
}
private void buttonTopHit_Click(object sender, RoutedEventArgs e)
{
if (buttonTopHit.Content.Equals("TH"))
{
inkCanvasTop.IsHitTestVisible = false;
buttonTopHit.Content = "Th";
}
else
{
inkCanvasTop.IsHitTestVisible = true;
buttonTopHit.Content = "TH";
}
}
private void buttonBottomHit_Click(object sender, RoutedEventArgs e)
{
if (buttonBottomHit.Content.Equals("BH"))
{
inkCanvasBottom.IsHitTestVisible = false;
buttonBottomHit.Content = "Bh";
}
else
{
inkCanvasBottom.IsHitTestVisible = true;
buttonBottomHit.Content = "BH";
}
}
private void inkCanvasTop_Loaded(object sender, RoutedEventArgs e)
{
addInputs(inkCanvasTop);
addInputs(inkCanvasBottom);
}
private void addInputs(InkCanvas inkCanvas)
{
inkCanvas.InkPresenter.InputDeviceTypes = CoreInputDeviceTypes.Pen | CoreInputDeviceTypes.Mouse;
}
}
I have created User control, added ComboBox in it as View1.
View1:-
<UserControl x:Class="XYZ.Views.ComboBoxView"
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="60" d:DesignWidth="600">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="150" />
<ColumnDefinition Width="300" />
<ColumnDefinition Width="200" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<TextBlock Grid.Row="1" Grid.Column="0" HorizontalAlignment="Right" VerticalAlignment="Center" Margin="5" Style="{StaticResource textControlText}" Text="{Binding Label}" />
<ComboBox Grid.Row="1" Grid.Column="1" Margin="5" SelectedItem="{Binding SelectedItem}" SelectedValue="{Binding Value}" ItemsSource="{Binding Items}" SelectedValuePath="Value" DisplayMemberPath="Ui" SelectedIndex="{Binding SelectedIndex}" Visibility="{Binding Visible}">
<ComboBox.ToolTip>
<ToolTip>
<TextBlock Text="{Binding Help}" FlowDirection="LeftToRight" TextWrapping="Wrap" MaxWidth="400"/>
</ToolTip>
</ComboBox.ToolTip>
</ComboBox>
</Grid>
</UserControl>
and i have corresponding View1Model with SelectedItem, SelectedIndex, ObservableCollection of list items and Visible property.
View1Model:-
class XyZComboBoxViewModel
{
private ObservableCollection<XyZListItem> _items;
public ObservableCollection<XyZListItem> Items
{
get { return _items; }
set { _items = value; }
}
private XyZListItem _selectedItem;
public XyZListItem SelectedItem
{
get { return _selectedItem; }
set {
some code here
}
}
private Enum _visible;
public Enum Visibile
{
get{return _visible}
set{return _visible=value //passing System.Windows.Visibility.Collapsed;}
}
private int _selectedIndex;
public int SelectedIndex
{
get { return _selectedIndex; }
set { _selectedIndex = value; }
}
}
I have another View2 and View2Model.
In View2Model I create Two View1model objects(i.e 2 ComboBox's) and bind it to second view View2.
<ItemsControl ItemsSource="{Binding Items}" IsTabStop="False" />
The Two ComboBox's(List Box User control's) getting displayed in the View2.
Now i want to hide the second ComboBox(with Visibility set to Collapsed) on selecting a item from the first ComboBox.
On Selecting an item from first ComboBox, I iterate over the View1Model objects in View2Model and setting the Second ComboBox Visible property value to Visibility.Collapsed.
The problem is I'm not able to hide the second ComboBox.
Please help me.
you can use the mentioned code.
private Visibility _comboboxvisibility;
public Visibility comboboxvisibility
{
get { return _comboboxvisibility; }
set { _comboboxvisibility = value; RaisePropertyChanged("comboboxvisibility"); }
}
private XyZListItem _selectedItem;
public XyZListItem SelectedItem
{
get { return _selectedItem; }
set {
comboboxvisibility = Visibility.Collapsed;
}
}
public void UpdateAttributes(ComboBox sender)
{
var definitions = _attributeDefinitions.ToList();
{
var combobox = cmbAttributeDefinition1;
if (sender != combobox && combobox.SelectedValue != null)
definitions.RemoveAll(
x => x.AttrID == (imProfileAttributeID)combobox.SelectedValue);
}
{
var combobox = cmbAttributeDefinition2;
if (sender != combobox && combobox.SelectedValue != null)
definitions.RemoveAll(
x => x.AttrID == (imProfileAttributeID)combobox.SelectedValue);
}
{
var combobox = cmbAttributeDefinition3;
if (sender != combobox && combobox.SelectedValue != null)
definitions.RemoveAll(
x => x.AttrID == (imProfileAttributeID)combobox.SelectedValue);
}
{
var combobox = cmbAttributeDefinition4;
if (sender != combobox && combobox.SelectedValue != null)
definitions.RemoveAll(
x => x.AttrID == (imProfileAttributeID)combobox.SelectedValue);
}
{
var combobox = cmbAttributeDefinition5;
if (sender != combobox && combobox.SelectedValue != null)
definitions.RemoveAll(
x => x.AttrID == (imProfileAttributeID)combobox.SelectedValue);
}
sender.DataSource = definitions;
sender.DisplayMember = "Caption";
sender.ValueMember = "AttrID";
}
private void cmbAttributeDefinition1_DropDown(object sender, EventArgs e)
{
UpdateAttributes(sender as ComboBox);
}
private void cmbAttributeDefinition5_DropDown(object sender, EventArgs e)
{
UpdateAttributes(sender as ComboBox);
}
private void cmbAttributeDefinition2_DropDown(object sender, EventArgs e)
{
UpdateAttributes(sender as ComboBox);
}
private void cmbAttributeDefinition3_DropDown(object sender, EventArgs e)
{
UpdateAttributes(sender as ComboBox);
}
private void cmbAttributeDefinition4_DropDown(object sender, EventArgs e)
{
UpdateAttributes(sender as ComboBox);
}
I have a small prototype that allows to add selected item from one listbox to another. I need to be able to select multiple item from listbox and move them to another and backward - from second listbox to first one. I am wondering if someone has good sample or can modify the code I already have. Thank you in advance.
Two listboxes and buttons XAML:
<Grid x:Name="LayoutRoot">
<Grid.ColumnDefinitions>
<ColumnDefinition/>
</Grid.ColumnDefinitions>
<Border Margin="0,40,225,20">
<ListBox x:Name="LeftListBox" SelectionMode="Multiple"/>
</Border>
<Border Margin="0,40,20,20" BorderThickness="1" BorderBrush="#FFCECECE" HorizontalAlignment="Right" Width="169" Padding="5" >
<ListBox x:Name="RightListBox" BorderThickness="0" />
</Border>
<Button x:Name="AddButton" Height="40" Margin="0,3,198,0" VerticalAlignment="Center" Click="AddButton_Click" HorizontalAlignment="Right" Width="15" Content="▶" />
<Button x:Name="RemoveButton" Height="40" Margin="0,94,198,0" VerticalAlignment="Center" Click="RemoveButton_Click" HorizontalAlignment="Right" Width="15" Content="R" />
</Grid>
Code behind:
public partial class SelectServersUC : UserControl
{
private ArrayList myDataList = null;
string currentItemText ;
int currentItemIndex ;
public SelectServersUC()
{
this.InitializeComponent();
myDataList = LoadListBoxData();
LeftListBox.ItemsSource = myDataList;
}
private void UserControl_Loaded(object sender, RoutedEventArgs e)
{
myDataList = LoadListBoxData();
LeftListBox.ItemsSource = myDataList;
}
private ArrayList LoadListBoxData()
{
ArrayList itemsList = new ArrayList();
itemsList.Add("Item1");
itemsList.Add("Item2");
itemsList.Add("Item3");
itemsList.Add("Item4");
itemsList.Add("Item5");
itemsList.Add("Item6");
itemsList.Add("Item7");
itemsList.Add("Item8");
itemsList.Add("Item9");
itemsList.Add("Item10");
return itemsList;
}
private void AddButton_Click(object sender, RoutedEventArgs e)
{
// Find the right item and it's value and index
currentItemText = LeftListBox.SelectedValue.ToString();
currentItemIndex = LeftListBox.SelectedIndex;
RightListBox.Items.Add(currentItemText);
if (myDataList != null)
{
myDataList.RemoveAt(currentItemIndex);
}
// Refresh data binding
ApplyDataBinding();
}
private void RemoveButton_Click(object sender, RoutedEventArgs e)
{
// Find the right item and it's value and index
currentItemText = RightListBox.SelectedValue.ToString();
currentItemIndex = RightListBox.SelectedIndex;
// Add RightListBox item to the ArrayList
myDataList.Add(currentItemText);
// LeftListBox.Items.Add(RightListBox.SelectedItem);
RightListBox.Items.RemoveAt(RightListBox.Items.IndexOf(RightListBox.SelectedItem));
// Refresh data binding
ApplyDataBinding();
}
/// <summary>
/// Refreshes data binding
/// </summary>
private void ApplyDataBinding()
{
LeftListBox.ItemsSource = null;
// Bind ArrayList with the ListBox
LeftListBox.ItemsSource = myDataList;
}
just have a look at this
Move items from one listbox to another
http://www.c-sharpcorner.com/UploadFile/mahesh/WPFListBoxDataTransfer07272008130032PM/WPFListBoxDataTransfer.aspx
public partial class listtolist : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
for (int i = ListBox1.Items.Count - 1; i >= 0; i--)
{
if (ListBox1.Items[i].Selected)
{
ListBox2.Items.Add(ListBox1.Items[i]);
ListBox1.Items.Remove(ListBox1.Items[i]);
}
}
}
protected void Button2_Click(object sender, EventArgs e)
{
for (int i = ListBox2.Items.Count - 1; i >= 0; i--)
{
if (ListBox2.Items[i].Selected)
{
ListBox1.Items.Add(ListBox2.Items[i]);
ListBox2.Items.Remove(ListBox2.Items[i]);
}
}
}
}