[英]Binding Issue in WPF
我有綁定問題,我試圖移動鼠標移動鼠標時,這是我的列表:
<ListBox x:Name="icTables" FlowDirection="LeftToRight" ItemsSource="{Binding Path=ocTablesinSection,UpdateSourceTrigger=PropertyChanged}" Margin="0,101,52,0" Grid.Column="1" SelectionMode="Extended" HorizontalAlignment="Right" Width="705" Height="400" VerticalAlignment="Top">
<ListBox.ItemsPanel>
<ItemsPanelTemplate>
<Canvas/>
</ItemsPanelTemplate>
</ListBox.ItemsPanel>
<ItemsControl.ItemContainerStyle>
<Style
TargetType="ListBoxItem">
<Setter Property="Canvas.Left" Value="{Binding Path=CLeft,UpdateSourceTrigger=PropertyChanged}"/>
<Setter Property="Canvas.Top" Value="{Binding Path=CTop,UpdateSourceTrigger=PropertyChanged}"/>
</Style>
</ItemsControl.ItemContainerStyle>
<ListBox.ItemTemplate>
<DataTemplate>
<Grid>
<Rectangle Width="50" Height="50" Fill="Red" Cursor="Hand" MouseDown="Rectangle_MouseDown" MouseUp="Rectangle_MouseUp" MouseMove="Rectangle_MouseMove" />
</Grid>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
在代碼隱藏的MouseMove事件中:
private void Rectangle_MouseMove(object sender, MouseEventArgs e)
{
if (isDraggingRectangle)
{
//
// Drag-move selected rectangles.
//
Point curMouseDownPoint = e.GetPosition(this);
var dragDelta = curMouseDownPoint - origMouseDownPoint;
origMouseDownPoint = curMouseDownPoint;
foreach (var item in ocTablesinSection)
{
item.CLeft += dragDelta.X;
item.CTop += dragDelta.Y;
}
}
else if (isLeftMouseDownOnRectangle)
{
//
// The user is left-dragging the rectangle,
// but don't initiate the drag operation until
// the mouse cursor has moved more than the threshold value.
//
Point curMouseDownPoint = e.GetPosition(this);
var dragDelta = curMouseDownPoint - origMouseDownPoint;
double dragDistance = Math.Abs(dragDelta.Length);
if (dragDistance > DragThreshold)
{
//
// When the mouse has been dragged more than the threshold value commence dragging the rectangle.
//
isDraggingRectangle = true;
}
e.Handled = true;
}
}
每件事都有效,但UI不顯示更新(矩形不移動),當我將CLeft和CTop更改為公共變量而窗口作為元素名稱時,它可以工作!!
我的代碼中有什么問題阻止矩形移動鼠標?
//更新 -
private ObservableCollection<TablesinSection> _ocTablesinSection;
public ObservableCollection ocTablesinSection {get {return _ocTablesinSection; } set {_ocTablesinSection = value; OnPropertyChanged( “ocTablesinSection”); }}
WPF綁定不適用於字段 。 它僅適用於properties
。
將它們聲明為屬性。
public double CLeft { get; set; }
public double CTop { get; set; }
此外,如果您想要更新任何屬性更改的UI,您必須在包含此屬性的類上實現INotifyPropertyChanged接口。
UPDATE
使屬性引發PropertyChangedEvent
:
private double cLeft;
public double CLeft
{
get
{
return cLeft;
}
set
{
if(cLeft != value)
{
cLeft = value;
OnPropertyChanged("CLeft");
}
}
}
同樣也為CTop
做同樣的CTop
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.