英文:
How to WPF Slider and Textbox two way binding?
问题
我想将 slider
的值绑定到 textbox
,并将 textbox
的值绑定到 slider
的值(用户交互)。
目前只能将 textbox
绑定到 slider
的值。如何实现双向绑定?
<TextBox
Width="70"
Height="20"
Grid.Row="1"
Margin="0 0 80 180"
x:Name="AO1text"
Text="{Binding ElementName=AOch1, Path=Value, StringFormat={}{0:F2}}"/>
<Slider
x:Name="AOch1"
Maximum="20"
Minimum="4"
Value="{Binding ao1value, Mode=TwoWay}"
Width="250"
BorderThickness="5"
TickPlacement="BottomRight"
不要回答我要翻译的问题。
英文:
i want slider
value to binding on textbox
and textbox
to slider
value(user interaction).
im now just textbox
binded of slider
value. How can i get it?
<TextBox
Width="70"
Height="20"
Grid.Row="1"
Margin="0 0 80 180"
x:Name="AO1text"
Text="{Binding ElementName=AOch1,Path=Value, StringFormat={}{0:F2}}"/>
<Slider
x:Name="AOch1"
Maximum="20"
Minimum="4"
Value="{Binding ao1value}"
Width="250"
BorderThickness="5"
TickPlacement="BottomRight"
答案1
得分: -1
<TextBox Width="120" Text="{Binding ElementName=AOch1, Path=Value, StringFormat={}{0:N0}, UpdateSourceTrigger=PropertyChanged}"/>
<Slider x:Name="AOch1" Maximum="100" Minimum="0" Width="250" />
// 从滑块获取值
targetObject.Value = AOch1.Value;
建议的方法是:
- 创建一个具有属性(例如 Value)的类
public class ItemModel
{
double _Value = 4;
public double Value
{
get => _Value;
set
{
if (value < 4)
value = 4;
if (value > 20)
value = 20;
if (_Value != value)
{
_Value = value;
// 通知属性更改
}
}
}
}
// Window1.xaml.cs
ItemModel model = new ItemModel();
// Window1_Loaded
yourGrid.DataContext = model;
- 将 ItemModel.Value 绑定到 TextBox.Text 和 Slider.Value。
<TextBox Text="{Binding Path=Value, StringFormat={}{0:F2}, UpdateSourceTrigger=PropertyChanged}"/>
<Slider Value="{Binding Path=Value}" Maximum="20" Minimum="4" Width="250" BorderThickness="5" TickPlacement="BottomRight" />
- 这样,在代码部分中,您只需要访问 ItemModel.Value。
英文:
try this
<TextBox Width="120" Text="{Binding ElementName=AOch1, Path=Value, StringFormat={}{0:N0}, UpdateSourceTrigger=PropertyChanged}"/>
<Slider x:Name="AOch1" Maximum="100" Minimum="0" Width="250" />
// Get value from Slider
targetObject.Value = AOch1.Value;
The recommended approach is:
- Create a class with property, like Value
public class ItemModel
{
double _Value = 4;
public double Value
{
get => _Value;
set
{
if (value < 4)
value = 4;
if (value > 20)
value = 20;
if (_Value != value)
{
_Value = value;
// Notify Property Changed
}
}
}
}
// Window1.xaml.cs
ItemModel model = new ItemModel();
// Window1_Loaded
yourGrid.DataContext = model;
- Bind ItemModel.Value to the TextBox.Text and Slider.Value.
<TextBox Text="{Binding Path=Value, StringFormat={}{0:F2}, UpdateSourceTrigger=PropertyChanged}"/>
<Slider Value="{Binding Path=Value}" Maximum="20" Minimum="4" Width="250" BorderThickness="5" TickPlacement="BottomRight" />
- In this way, in the code section, you only need to access ItemModel.Value.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论